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>
43 #include "linux_usbfs.h"
46 * opening a usbfs node causes the device to be resumed, so we attempt to
47 * avoid this during enumeration.
49 * sysfs allows us to read the kernel's in-memory copies of device descriptors
50 * and so forth, avoiding the need to open the device:
51 * - The binary "descriptors" file contains all config descriptors since
52 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
53 * - The binary "descriptors" file was added in 2.6.23, commit
54 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
55 * active config descriptors
56 * - The "busnum" file was added in 2.6.22, commit
57 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
58 * - The "devnum" file has been present since pre-2.6.18
59 * - the "bConfigurationValue" file has been present since pre-2.6.18
61 * If we have bConfigurationValue, busnum, and devnum, then we can determine
62 * the active configuration without having to open the usbfs node in RDWR mode.
63 * The busnum file is important as that is the only way we can relate sysfs
64 * devices to usbfs nodes.
66 * If we also have all descriptors, we can obtain the device descriptor and
67 * configuration without touching usbfs at all.
70 /* endianness for multi-byte fields:
72 * Descriptors exposed by usbfs have the multi-byte fields in the device
73 * descriptor as host endian. Multi-byte fields in the other descriptors are
74 * bus-endian. The kernel documentation says otherwise, but it is wrong.
76 * In sysfs all descriptors are bus-endian.
79 static const char *usbfs_path = NULL;
81 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
82 static int usbdev_names = 0;
84 /* Linux has changed the maximum length of an individual isochronous packet
85 * over time. Initially this limit was 1,023 bytes, but Linux 2.6.18
86 * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
87 * 8,192 bytes to support higher bandwidth devices. Linux 3.10
88 * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
89 * value to 49,152 bytes to support super speed devices.
91 static unsigned int max_iso_packet_len = 0;
93 /* Linux 2.6.23 adds support for O_CLOEXEC when opening files, which marks the
94 * close-on-exec flag in the underlying file descriptor. */
95 static int supports_flag_cloexec = -1;
97 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
98 * allows us to mark URBs as being part of a specific logical transfer when
99 * we submit them to the kernel. then, on any error except a cancellation, all
100 * URBs within that transfer will be cancelled and no more URBs will be
101 * accepted for the transfer, meaning that no more data can creep in.
103 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
104 * (in either direction) except the first.
105 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
106 * last; it means that the kernel should treat a short reply as an error.
107 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
108 * transfers can't be short unless there's already some sort of error), and
109 * setting this flag is disallowed (a kernel with USB debugging enabled will
112 static int supports_flag_bulk_continuation = -1;
114 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
115 * allows us to mark URBs that should be followed by a zero length data
116 * packet, which can be required by device- or class-specific protocols.
118 static int supports_flag_zero_packet = -1;
120 /* clock ID for monotonic clock, as not all clock sources are available on all
121 * systems. appropriate choice made at initialization time. */
122 static clockid_t monotonic_clkid = -1;
124 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
125 * to sysfs, so we can relate devices. This also implies that we can read
126 * the active configuration through bConfigurationValue */
127 static int sysfs_can_relate_devices = -1;
129 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
130 * config descriptors (rather then just the active config) to the sysfs
131 * descriptors file, so from then on we can use them. */
132 static int sysfs_has_descriptors = -1;
134 /* how many times have we initted (and not exited) ? */
135 static int init_count = 0;
137 /* Serialize hotplug start/stop */
138 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
139 /* Serialize scan-devices, event-thread, and poll */
140 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
142 static int linux_start_event_monitor(void);
143 static int linux_stop_event_monitor(void);
144 static int linux_scan_devices(struct libusb_context *ctx);
145 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
146 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
148 #if !defined(USE_UDEV)
149 static int linux_default_scan_devices (struct libusb_context *ctx);
152 struct kernel_version {
158 struct linux_device_priv {
160 unsigned char *descriptors;
162 int active_config; /* cache val for !sysfs_can_relate_devices */
165 struct linux_device_handle_priv {
174 /* submission failed after the first URB, so await cancellation/completion
175 * of all the others */
178 /* cancelled by user or timeout */
181 /* completed multi-URB transfer in non-final URB */
184 /* one or more urbs encountered a low-level error */
188 struct linux_transfer_priv {
190 struct usbfs_urb *urbs;
191 struct usbfs_urb **iso_urbs;
194 enum reap_action reap_action;
197 enum libusb_transfer_status reap_status;
199 /* next iso packet in user-supplied transfer to be populated */
200 int iso_packet_offset;
203 static int _open(const char *path, int flags)
205 #if defined(O_CLOEXEC)
206 if (supports_flag_cloexec)
207 return open(path, flags | O_CLOEXEC);
210 return open(path, flags);
213 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
215 struct libusb_context *ctx = DEVICE_CTX(dev);
221 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
222 usbfs_path, dev->bus_number, dev->device_address);
224 snprintf(path, PATH_MAX, "%s/%03d/%03d",
225 usbfs_path, dev->bus_number, dev->device_address);
227 fd = _open(path, mode);
229 return fd; /* Success */
231 if (errno == ENOENT) {
233 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
235 /* Wait 10ms for USB device path creation.*/
236 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
238 fd = _open(path, mode);
240 return fd; /* Success */
244 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
245 path, strerror(errno));
246 if (errno == EACCES && mode == O_RDWR)
247 usbi_err(ctx, "libusb requires write access to USB "
252 return LIBUSB_ERROR_ACCESS;
254 return LIBUSB_ERROR_NO_DEVICE;
255 return LIBUSB_ERROR_IO;
258 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
260 return (struct linux_device_priv *) dev->os_priv;
263 static struct linux_device_handle_priv *_device_handle_priv(
264 struct libusb_device_handle *handle)
266 return (struct linux_device_handle_priv *) handle->os_priv;
269 /* check dirent for a /dev/usbdev%d.%d name
270 * optionally return bus/device on success */
271 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
275 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
278 usbi_dbg("found: %s", entry->d_name);
286 static int check_usb_vfs(const char *dirname)
289 struct dirent *entry;
292 dir = opendir(dirname);
296 while ((entry = readdir(dir)) != NULL) {
297 if (entry->d_name[0] == '.')
300 /* We assume if we find any files that it must be the right place */
309 static const char *find_usbfs_path(void)
311 const char *path = "/dev/bus/usb";
312 const char *ret = NULL;
314 if (check_usb_vfs(path)) {
317 path = "/proc/bus/usb";
318 if (check_usb_vfs(path))
322 /* look for /dev/usbdev*.* if the normal places fail */
324 struct dirent *entry;
330 while ((entry = readdir(dir)) != NULL) {
331 if (_is_usbdev_entry(entry, NULL, NULL)) {
332 /* found one; that's enough */
342 /* On udev based systems without any usb-devices /dev/bus/usb will not
343 * exist. So if we've not found anything and we're using udev for hotplug
344 * simply assume /dev/bus/usb rather then making libusb_init fail. */
345 #if defined(USE_UDEV)
347 ret = "/dev/bus/usb";
351 usbi_dbg("found usbfs at %s", ret);
356 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
357 * seem to lack it). fall back to REALTIME if we have to. */
358 static clockid_t find_monotonic_clock(void)
360 #ifdef CLOCK_MONOTONIC
364 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
365 * because it's not available through timerfd */
366 r = clock_gettime(CLOCK_MONOTONIC, &ts);
368 return CLOCK_MONOTONIC;
369 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
372 return CLOCK_REALTIME;
375 static int get_kernel_version(struct libusb_context *ctx,
376 struct kernel_version *ver)
381 if (uname(&uts) < 0) {
382 usbi_err(ctx, "uname failed, errno %d", errno);
386 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
388 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
397 usbi_dbg("reported kernel version is %s", uts.release);
402 static int kernel_version_ge(const struct kernel_version *ver,
403 int major, int minor, int sublevel)
405 if (ver->major > major)
407 else if (ver->major < major)
410 /* kmajor == major */
411 if (ver->minor == -1 && ver->sublevel == -1)
412 return 0 == minor && 0 == sublevel;
413 else if (ver->minor > minor)
415 else if (ver->minor < minor)
418 /* kminor == minor */
419 if (ver->sublevel == -1)
420 return 0 == sublevel;
422 return ver->sublevel >= sublevel;
425 static int op_init(struct libusb_context *ctx)
427 struct kernel_version kversion;
431 usbfs_path = find_usbfs_path();
433 usbi_err(ctx, "could not find usbfs");
434 return LIBUSB_ERROR_OTHER;
437 if (monotonic_clkid == -1)
438 monotonic_clkid = find_monotonic_clock();
440 if (get_kernel_version(ctx, &kversion) < 0)
441 return LIBUSB_ERROR_OTHER;
443 if (supports_flag_cloexec == -1) {
444 /* O_CLOEXEC flag available from Linux 2.6.23 */
445 supports_flag_cloexec = kernel_version_ge(&kversion,2,6,23);
448 if (supports_flag_bulk_continuation == -1) {
449 /* bulk continuation URB flag available from Linux 2.6.32 */
450 supports_flag_bulk_continuation = kernel_version_ge(&kversion,2,6,32);
453 if (supports_flag_bulk_continuation)
454 usbi_dbg("bulk continuation flag supported");
456 if (-1 == supports_flag_zero_packet) {
457 /* zero length packet URB flag fixed since Linux 2.6.31 */
458 supports_flag_zero_packet = kernel_version_ge(&kversion,2,6,31);
461 if (supports_flag_zero_packet)
462 usbi_dbg("zero length packet flag supported");
464 if (!max_iso_packet_len) {
465 if (kernel_version_ge(&kversion,3,10,0))
466 max_iso_packet_len = 49152;
467 else if (kernel_version_ge(&kversion,2,6,18))
468 max_iso_packet_len = 8192;
470 max_iso_packet_len = 1023;
473 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
475 if (-1 == sysfs_has_descriptors) {
476 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
477 sysfs_has_descriptors = kernel_version_ge(&kversion,2,6,26);
480 if (-1 == sysfs_can_relate_devices) {
481 /* sysfs has busnum since Linux 2.6.22 */
482 sysfs_can_relate_devices = kernel_version_ge(&kversion,2,6,22);
485 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
486 r = stat(SYSFS_DEVICE_PATH, &statbuf);
487 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
488 usbi_warn(ctx, "sysfs not mounted");
489 sysfs_can_relate_devices = 0;
490 sysfs_has_descriptors = 0;
494 if (sysfs_can_relate_devices)
495 usbi_dbg("sysfs can relate devices");
497 if (sysfs_has_descriptors)
498 usbi_dbg("sysfs has complete descriptors");
500 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
502 if (init_count == 0) {
503 /* start up hotplug event handler */
504 r = linux_start_event_monitor();
506 if (r == LIBUSB_SUCCESS) {
507 r = linux_scan_devices(ctx);
508 if (r == LIBUSB_SUCCESS)
510 else if (init_count == 0)
511 linux_stop_event_monitor();
513 usbi_err(ctx, "error starting hotplug event monitor");
514 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
519 static void op_exit(struct libusb_context *ctx)
522 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
523 assert(init_count != 0);
525 /* tear down event handler */
526 (void)linux_stop_event_monitor();
528 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
531 static int linux_start_event_monitor(void)
533 #if defined(USE_UDEV)
534 return linux_udev_start_event_monitor();
536 return linux_netlink_start_event_monitor();
540 static int linux_stop_event_monitor(void)
542 #if defined(USE_UDEV)
543 return linux_udev_stop_event_monitor();
545 return linux_netlink_stop_event_monitor();
549 static int linux_scan_devices(struct libusb_context *ctx)
553 usbi_mutex_static_lock(&linux_hotplug_lock);
555 #if defined(USE_UDEV)
556 ret = linux_udev_scan_devices(ctx);
558 ret = linux_default_scan_devices(ctx);
561 usbi_mutex_static_unlock(&linux_hotplug_lock);
566 static void op_hotplug_poll(void)
568 #if defined(USE_UDEV)
569 linux_udev_hotplug_poll();
571 linux_netlink_hotplug_poll();
575 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
577 struct linux_device_priv *priv = _device_priv(dev);
578 char filename[PATH_MAX];
581 snprintf(filename, PATH_MAX, "%s/%s/%s",
582 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
583 fd = _open(filename, O_RDONLY);
585 usbi_err(DEVICE_CTX(dev),
586 "open %s failed ret=%d errno=%d", filename, fd, errno);
587 return LIBUSB_ERROR_IO;
593 /* Note only suitable for attributes which always read >= 0, < 0 is error */
594 static int __read_sysfs_attr(struct libusb_context *ctx,
595 const char *devname, const char *attr)
597 char filename[PATH_MAX];
601 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
603 fd = _open(filename, O_RDONLY);
605 if (errno == ENOENT) {
606 /* File doesn't exist. Assume the device has been
607 disconnected (see trac ticket #70). */
608 return LIBUSB_ERROR_NO_DEVICE;
610 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
611 return LIBUSB_ERROR_IO;
616 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
618 return LIBUSB_ERROR_OTHER;
621 r = fscanf(f, "%d", &value);
624 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
625 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
628 usbi_err(ctx, "%s contains a negative value", filename);
629 return LIBUSB_ERROR_IO;
635 static int op_get_device_descriptor(struct libusb_device *dev,
636 unsigned char *buffer, int *host_endian)
638 struct linux_device_priv *priv = _device_priv(dev);
640 *host_endian = (priv->sysfs_dir && sysfs_has_descriptors) ? 0 : 1;
641 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
646 /* read the bConfigurationValue for a device */
647 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
650 char tmp[5] = {0, 0, 0, 0, 0};
655 fd = _open_sysfs_attr(dev, "bConfigurationValue");
659 r = read(fd, tmp, sizeof(tmp));
662 usbi_err(DEVICE_CTX(dev),
663 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
664 return LIBUSB_ERROR_IO;
666 usbi_dbg("device unconfigured");
671 if (tmp[sizeof(tmp) - 1] != 0) {
672 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
673 return LIBUSB_ERROR_IO;
674 } else if (tmp[0] == 0) {
675 usbi_err(DEVICE_CTX(dev), "no configuration value?");
676 return LIBUSB_ERROR_IO;
679 num = strtol(tmp, &endptr, 10);
681 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
682 return LIBUSB_ERROR_IO;
689 int linux_get_device_address (struct libusb_context *ctx, int detached,
690 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
691 const char *sys_name, int fd)
693 char proc_path[PATH_MAX], fd_path[PATH_MAX];
697 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
698 /* can't use sysfs to read the bus and device number if the
699 * device has been detached */
700 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
701 if (NULL == dev_node && fd >= 0) {
702 /* try to retrieve the device node from fd */
703 snprintf(proc_path, PATH_MAX, "/proc/self/fd/%d", fd);
704 r = readlink(proc_path, fd_path, PATH_MAX);
708 if (NULL == dev_node) {
709 return LIBUSB_ERROR_OTHER;
712 /* will this work with all supported kernel versions? */
713 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
714 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
715 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
716 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
718 return LIBUSB_ERROR_OTHER;
721 return LIBUSB_SUCCESS;
724 usbi_dbg("scan %s", sys_name);
726 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
729 if (sysfs_attr > 255)
730 return LIBUSB_ERROR_INVALID_PARAM;
731 *busnum = (uint8_t) sysfs_attr;
733 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
736 if (sysfs_attr > 255)
737 return LIBUSB_ERROR_INVALID_PARAM;
739 *devaddr = (uint8_t) sysfs_attr;
741 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
743 return LIBUSB_SUCCESS;
746 /* Return offset of the next descriptor with the given type */
747 static int seek_to_next_descriptor(struct libusb_context *ctx,
748 uint8_t descriptor_type, unsigned char *buffer, int size)
750 struct usb_descriptor_header header;
753 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
755 return LIBUSB_ERROR_NOT_FOUND;
758 usbi_err(ctx, "short descriptor read %d/2", size);
759 return LIBUSB_ERROR_IO;
761 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
763 if (i && header.bDescriptorType == descriptor_type)
766 usbi_err(ctx, "bLength overflow by %d bytes", -size);
767 return LIBUSB_ERROR_IO;
770 /* Return offset to next config */
771 static int seek_to_next_config(struct libusb_device *dev,
772 unsigned char *buffer, int size)
774 struct libusb_context *ctx = DEVICE_CTX(dev);
775 struct linux_device_priv *priv = _device_priv(dev);
776 struct libusb_config_descriptor config;
779 return LIBUSB_ERROR_NOT_FOUND;
781 if (size < LIBUSB_DT_CONFIG_SIZE) {
782 usbi_err(ctx, "short descriptor read %d/%d",
783 size, LIBUSB_DT_CONFIG_SIZE);
784 return LIBUSB_ERROR_IO;
787 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
788 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
789 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
790 config.bDescriptorType);
791 return LIBUSB_ERROR_IO;
795 * In usbfs the config descriptors are config.wTotalLength bytes apart,
796 * with any short reads from the device appearing as holes in the file.
798 * In sysfs wTotalLength is ignored, instead the kernel returns a
799 * config descriptor with verified bLength fields, with descriptors
800 * with an invalid bLength removed.
802 if (priv->sysfs_dir && sysfs_has_descriptors) {
803 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
805 if (next == LIBUSB_ERROR_NOT_FOUND)
810 if (next != config.wTotalLength)
811 usbi_warn(ctx, "config length mismatch wTotalLength "
812 "%d real %d", config.wTotalLength, next);
815 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
816 usbi_err(ctx, "invalid wTotalLength %d",
817 config.wTotalLength);
818 return LIBUSB_ERROR_IO;
819 } else if (config.wTotalLength > size) {
820 usbi_warn(ctx, "short descriptor read %d/%d",
821 size, config.wTotalLength);
824 return config.wTotalLength;
828 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
829 uint8_t value, unsigned char **buffer, int *host_endian)
831 struct linux_device_priv *priv = _device_priv(dev);
832 unsigned char *descriptors = priv->descriptors;
833 int size = priv->descriptors_len;
834 struct libusb_config_descriptor *config;
837 /* Unlike the device desc. config descs. are always in raw format */
840 /* Skip device header */
841 descriptors += DEVICE_DESC_LENGTH;
842 size -= DEVICE_DESC_LENGTH;
844 /* Seek till the config is found, or till "EOF" */
846 int next = seek_to_next_config(dev, descriptors, size);
849 config = (struct libusb_config_descriptor *)descriptors;
850 if (config->bConfigurationValue == value) {
851 *buffer = descriptors;
859 static int op_get_active_config_descriptor(struct libusb_device *dev,
860 unsigned char *buffer, size_t len, int *host_endian)
862 struct linux_device_priv *priv = _device_priv(dev);
864 unsigned char *config_desc;
866 if (priv->sysfs_dir && sysfs_can_relate_devices) {
867 r = sysfs_get_active_config(dev, &config);
871 /* Use cached bConfigurationValue */
872 config = priv->active_config;
875 return LIBUSB_ERROR_NOT_FOUND;
877 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
882 len = MIN(len, (size_t)r);
883 memcpy(buffer, config_desc, len);
887 static int op_get_config_descriptor(struct libusb_device *dev,
888 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
890 struct linux_device_priv *priv = _device_priv(dev);
891 unsigned char *descriptors = priv->descriptors;
892 int i, r, size = priv->descriptors_len;
894 /* Unlike the device desc. config descs. are always in raw format */
897 /* Skip device header */
898 descriptors += DEVICE_DESC_LENGTH;
899 size -= DEVICE_DESC_LENGTH;
901 /* Seek till the config is found, or till "EOF" */
903 r = seek_to_next_config(dev, descriptors, size);
906 if (i == config_index)
912 len = MIN(len, (size_t)r);
913 memcpy(buffer, descriptors, len);
917 /* send a control message to retrieve active configuration */
918 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
920 struct linux_device_priv *priv = _device_priv(dev);
921 unsigned char active_config = 0;
924 struct usbfs_ctrltransfer ctrl = {
925 .bmRequestType = LIBUSB_ENDPOINT_IN,
926 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
931 .data = &active_config
934 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
937 return LIBUSB_ERROR_NO_DEVICE;
939 /* we hit this error path frequently with buggy devices :( */
940 usbi_warn(DEVICE_CTX(dev),
941 "get_configuration failed ret=%d errno=%d", r, errno);
942 priv->active_config = -1;
944 if (active_config > 0) {
945 priv->active_config = active_config;
947 /* some buggy devices have a configuration 0, but we're
948 * reaching into the corner of a corner case here, so let's
949 * not support buggy devices in these circumstances.
950 * stick to the specs: a configuration value of 0 means
952 usbi_warn(DEVICE_CTX(dev),
953 "active cfg 0? assuming unconfigured device");
954 priv->active_config = -1;
958 return LIBUSB_SUCCESS;
961 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
962 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
964 struct linux_device_priv *priv = _device_priv(dev);
965 struct libusb_context *ctx = DEVICE_CTX(dev);
966 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
970 dev->bus_number = busnum;
971 dev->device_address = devaddr;
974 priv->sysfs_dir = strdup(sysfs_dir);
975 if (!priv->sysfs_dir)
976 return LIBUSB_ERROR_NO_MEM;
978 /* Note speed can contain 1.5, in this case __read_sysfs_attr
979 will stop parsing at the '.' and return 1 */
980 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
983 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
984 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
985 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
986 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
987 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
989 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
994 /* cache descriptors in memory */
995 if (sysfs_dir && sysfs_has_descriptors) {
996 fd = _open_sysfs_attr(dev, "descriptors");
997 } else if (wrapped_fd < 0) {
998 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1001 r = lseek(fd, 0, SEEK_SET);
1003 usbi_err(ctx, "seek failed ret=%d errno=%d", r, errno);
1004 return LIBUSB_ERROR_IO;
1011 descriptors_size *= 2;
1012 priv->descriptors = usbi_reallocf(priv->descriptors,
1014 if (!priv->descriptors) {
1015 if (fd != wrapped_fd)
1017 return LIBUSB_ERROR_NO_MEM;
1019 /* usbfs has holes in the file */
1020 if (!(sysfs_dir && sysfs_has_descriptors)) {
1021 memset(priv->descriptors + priv->descriptors_len,
1022 0, descriptors_size - priv->descriptors_len);
1024 r = read(fd, priv->descriptors + priv->descriptors_len,
1025 descriptors_size - priv->descriptors_len);
1027 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1029 if (fd != wrapped_fd)
1031 return LIBUSB_ERROR_IO;
1033 priv->descriptors_len += r;
1034 } while (priv->descriptors_len == descriptors_size);
1036 if (fd != wrapped_fd)
1039 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1040 usbi_err(ctx, "short descriptor read (%d)",
1041 priv->descriptors_len);
1042 return LIBUSB_ERROR_IO;
1045 if (sysfs_dir && sysfs_can_relate_devices)
1046 return LIBUSB_SUCCESS;
1048 /* cache active config */
1050 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1054 /* cannot send a control message to determine the active
1055 * config. just assume the first one is active. */
1056 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1057 "active configuration descriptor");
1058 if (priv->descriptors_len >=
1059 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1060 struct libusb_config_descriptor config;
1061 usbi_parse_descriptor(
1062 priv->descriptors + DEVICE_DESC_LENGTH,
1063 "bbwbbbbb", &config, 0);
1064 priv->active_config = config.bConfigurationValue;
1066 priv->active_config = -1; /* No config dt */
1068 return LIBUSB_SUCCESS;
1071 r = usbfs_get_active_config(dev, fd);
1078 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1080 struct libusb_context *ctx = DEVICE_CTX(dev);
1081 struct libusb_device *it;
1082 char *parent_sysfs_dir, *tmp;
1083 int ret, add_parent = 1;
1085 /* XXX -- can we figure out the topology when using usbfs? */
1086 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1087 /* either using usbfs or finding the parent of a root hub */
1088 return LIBUSB_SUCCESS;
1091 parent_sysfs_dir = strdup(sysfs_dir);
1092 if (NULL == parent_sysfs_dir) {
1093 return LIBUSB_ERROR_NO_MEM;
1095 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1096 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1097 dev->port_number = atoi(tmp + 1);
1100 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1102 free (parent_sysfs_dir);
1103 return LIBUSB_SUCCESS;
1106 /* is the parent a root hub? */
1107 if (NULL == strchr(parent_sysfs_dir, '-')) {
1108 tmp = parent_sysfs_dir;
1109 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1112 return LIBUSB_ERROR_NO_MEM;
1117 /* find the parent in the context */
1118 usbi_mutex_lock(&ctx->usb_devs_lock);
1119 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1120 struct linux_device_priv *priv = _device_priv(it);
1121 if (priv->sysfs_dir) {
1122 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1123 dev->parent_dev = libusb_ref_device(it);
1128 usbi_mutex_unlock(&ctx->usb_devs_lock);
1130 if (!dev->parent_dev && add_parent) {
1131 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1133 sysfs_scan_device(ctx, parent_sysfs_dir);
1138 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1139 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1141 free (parent_sysfs_dir);
1143 return LIBUSB_SUCCESS;
1146 int linux_enumerate_device(struct libusb_context *ctx,
1147 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1149 unsigned long session_id;
1150 struct libusb_device *dev;
1153 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1154 * will be reused. instead we should add a simple sysfs attribute with
1156 session_id = busnum << 8 | devaddr;
1157 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1160 dev = usbi_get_device_by_session_id(ctx, session_id);
1162 /* device already exists in the context */
1163 usbi_dbg("session_id %ld already exists", session_id);
1164 libusb_unref_device(dev);
1165 return LIBUSB_SUCCESS;
1168 usbi_dbg("allocating new device for %d/%d (session %ld)",
1169 busnum, devaddr, session_id);
1170 dev = usbi_alloc_device(ctx, session_id);
1172 return LIBUSB_ERROR_NO_MEM;
1174 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1177 r = usbi_sanitize_device(dev);
1181 r = linux_get_parent_info(dev, sysfs_dir);
1186 libusb_unref_device(dev);
1188 usbi_connect_device(dev);
1193 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1195 struct libusb_context *ctx;
1197 usbi_mutex_static_lock(&active_contexts_lock);
1198 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1199 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1201 usbi_mutex_static_unlock(&active_contexts_lock);
1204 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1206 struct libusb_context *ctx;
1207 struct libusb_device *dev;
1208 unsigned long session_id = busnum << 8 | devaddr;
1210 usbi_mutex_static_lock(&active_contexts_lock);
1211 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1212 dev = usbi_get_device_by_session_id (ctx, session_id);
1214 usbi_disconnect_device (dev);
1215 libusb_unref_device(dev);
1217 usbi_dbg("device not found for session %x", session_id);
1220 usbi_mutex_static_unlock(&active_contexts_lock);
1223 #if !defined(USE_UDEV)
1224 /* open a bus directory and adds all discovered devices to the context */
1225 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1228 char dirpath[PATH_MAX];
1229 struct dirent *entry;
1230 int r = LIBUSB_ERROR_IO;
1232 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1233 usbi_dbg("%s", dirpath);
1234 dir = opendir(dirpath);
1236 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1237 /* FIXME: should handle valid race conditions like hub unplugged
1238 * during directory iteration - this is not an error */
1242 while ((entry = readdir(dir))) {
1245 if (entry->d_name[0] == '.')
1248 devaddr = atoi(entry->d_name);
1250 usbi_dbg("unknown dir entry %s", entry->d_name);
1254 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1255 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1266 static int usbfs_get_device_list(struct libusb_context *ctx)
1268 struct dirent *entry;
1269 DIR *buses = opendir(usbfs_path);
1273 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1274 return LIBUSB_ERROR_IO;
1277 while ((entry = readdir(buses))) {
1280 if (entry->d_name[0] == '.')
1285 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1288 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1290 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1294 busnum = atoi(entry->d_name);
1296 usbi_dbg("unknown dir entry %s", entry->d_name);
1300 r = usbfs_scan_busdir(ctx, busnum);
1312 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1314 uint8_t busnum, devaddr;
1317 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname, -1);
1318 if (LIBUSB_SUCCESS != ret) {
1322 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1326 #if !defined(USE_UDEV)
1327 static int sysfs_get_device_list(struct libusb_context *ctx)
1329 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1330 struct dirent *entry;
1331 int num_devices = 0;
1332 int num_enumerated = 0;
1335 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1336 return LIBUSB_ERROR_IO;
1339 while ((entry = readdir(devices))) {
1340 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1341 || strchr(entry->d_name, ':'))
1346 if (sysfs_scan_device(ctx, entry->d_name)) {
1347 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1356 /* successful if at least one device was enumerated or no devices were found */
1357 if (num_enumerated || !num_devices)
1358 return LIBUSB_SUCCESS;
1360 return LIBUSB_ERROR_IO;
1363 static int linux_default_scan_devices (struct libusb_context *ctx)
1365 /* we can retrieve device list and descriptors from sysfs or usbfs.
1366 * sysfs is preferable, because if we use usbfs we end up resuming
1367 * any autosuspended USB devices. however, sysfs is not available
1368 * everywhere, so we need a usbfs fallback too.
1370 * as described in the "sysfs vs usbfs" comment at the top of this
1371 * file, sometimes we have sysfs but not enough information to
1372 * relate sysfs devices to usbfs nodes. op_init() determines the
1373 * adequacy of sysfs and sets sysfs_can_relate_devices.
1375 if (sysfs_can_relate_devices != 0)
1376 return sysfs_get_device_list(ctx);
1378 return usbfs_get_device_list(ctx);
1382 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1384 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1389 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1391 if (errno == ENOTTY)
1392 usbi_dbg("getcap not available");
1394 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1396 if (supports_flag_zero_packet)
1397 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1398 if (supports_flag_bulk_continuation)
1399 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1402 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1405 static int op_wrap_sys_device(struct libusb_context *ctx,
1406 struct libusb_device_handle *handle, intptr_t sys_dev)
1408 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1409 int fd = (int)sys_dev;
1410 uint8_t busnum, devaddr;
1411 struct usbfs_connectinfo ci;
1412 struct libusb_device *dev;
1415 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1417 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1419 usbi_err(ctx, "connectinfo failed (%d)", errno);
1420 return LIBUSB_ERROR_IO;
1422 /* There is no ioctl to get the bus number. We choose 0 here
1423 * as linux starts numbering buses from 1. */
1425 devaddr = ci.devnum;
1428 /* Session id is unused as we do not add the device to the list of
1429 * connected devices. */
1430 usbi_dbg("allocating new device for fd %d", fd);
1431 dev = usbi_alloc_device(ctx, 0);
1433 return LIBUSB_ERROR_NO_MEM;
1435 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1438 r = usbi_sanitize_device(dev);
1441 /* Consider the device as connected, but do not add it to the managed
1446 r = initialize_handle(handle, fd);
1451 libusb_unref_device(dev);
1455 static int op_open(struct libusb_device_handle *handle)
1459 fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1461 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1462 /* device will still be marked as attached if hotplug monitor thread
1463 * hasn't processed remove event yet */
1464 usbi_mutex_static_lock(&linux_hotplug_lock);
1465 if (handle->dev->attached) {
1466 usbi_dbg("open failed with no device, but device still attached");
1467 linux_device_disconnected(handle->dev->bus_number,
1468 handle->dev->device_address);
1470 usbi_mutex_static_unlock(&linux_hotplug_lock);
1475 r = initialize_handle(handle, fd);
1482 static void op_close(struct libusb_device_handle *dev_handle)
1484 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1485 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1486 if (!hpriv->fd_removed)
1487 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1488 if (!hpriv->fd_keep)
1492 static int op_get_configuration(struct libusb_device_handle *handle,
1495 struct linux_device_priv *priv = _device_priv(handle->dev);
1498 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1499 r = sysfs_get_active_config(handle->dev, config);
1501 r = usbfs_get_active_config(handle->dev,
1502 _device_handle_priv(handle)->fd);
1503 if (r == LIBUSB_SUCCESS)
1504 *config = priv->active_config;
1509 if (*config == -1) {
1510 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1517 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1519 struct linux_device_priv *priv = _device_priv(handle->dev);
1520 int fd = _device_handle_priv(handle)->fd;
1521 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1523 if (errno == EINVAL)
1524 return LIBUSB_ERROR_NOT_FOUND;
1525 else if (errno == EBUSY)
1526 return LIBUSB_ERROR_BUSY;
1527 else if (errno == ENODEV)
1528 return LIBUSB_ERROR_NO_DEVICE;
1530 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1531 return LIBUSB_ERROR_OTHER;
1534 /* update our cached active config descriptor */
1535 priv->active_config = config;
1537 return LIBUSB_SUCCESS;
1540 static int claim_interface(struct libusb_device_handle *handle, int iface)
1542 int fd = _device_handle_priv(handle)->fd;
1543 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1545 if (errno == ENOENT)
1546 return LIBUSB_ERROR_NOT_FOUND;
1547 else if (errno == EBUSY)
1548 return LIBUSB_ERROR_BUSY;
1549 else if (errno == ENODEV)
1550 return LIBUSB_ERROR_NO_DEVICE;
1552 usbi_err(HANDLE_CTX(handle),
1553 "claim interface failed, error %d errno %d", r, errno);
1554 return LIBUSB_ERROR_OTHER;
1559 static int release_interface(struct libusb_device_handle *handle, int iface)
1561 int fd = _device_handle_priv(handle)->fd;
1562 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1564 if (errno == ENODEV)
1565 return LIBUSB_ERROR_NO_DEVICE;
1567 usbi_err(HANDLE_CTX(handle),
1568 "release interface failed, error %d errno %d", r, errno);
1569 return LIBUSB_ERROR_OTHER;
1574 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1577 int fd = _device_handle_priv(handle)->fd;
1578 struct usbfs_setinterface setintf;
1581 setintf.interface = iface;
1582 setintf.altsetting = altsetting;
1583 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1585 if (errno == EINVAL)
1586 return LIBUSB_ERROR_NOT_FOUND;
1587 else if (errno == ENODEV)
1588 return LIBUSB_ERROR_NO_DEVICE;
1590 usbi_err(HANDLE_CTX(handle),
1591 "setintf failed error %d errno %d", r, errno);
1592 return LIBUSB_ERROR_OTHER;
1598 static int op_clear_halt(struct libusb_device_handle *handle,
1599 unsigned char endpoint)
1601 int fd = _device_handle_priv(handle)->fd;
1602 unsigned int _endpoint = endpoint;
1603 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1605 if (errno == ENOENT)
1606 return LIBUSB_ERROR_NOT_FOUND;
1607 else if (errno == ENODEV)
1608 return LIBUSB_ERROR_NO_DEVICE;
1610 usbi_err(HANDLE_CTX(handle),
1611 "clear_halt failed error %d errno %d", r, errno);
1612 return LIBUSB_ERROR_OTHER;
1618 static int op_reset_device(struct libusb_device_handle *handle)
1620 int fd = _device_handle_priv(handle)->fd;
1623 /* Doing a device reset will cause the usbfs driver to get unbound
1624 from any interfaces it is bound to. By voluntarily unbinding
1625 the usbfs driver ourself, we stop the kernel from rebinding
1626 the interface after reset (which would end up with the interface
1627 getting bound to the in kernel driver if any). */
1628 for (i = 0; i < USB_MAXINTERFACES; i++) {
1629 if (handle->claimed_interfaces & (1L << i)) {
1630 release_interface(handle, i);
1634 usbi_mutex_lock(&handle->lock);
1635 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1637 if (errno == ENODEV) {
1638 ret = LIBUSB_ERROR_NOT_FOUND;
1642 usbi_err(HANDLE_CTX(handle),
1643 "reset failed error %d errno %d", r, errno);
1644 ret = LIBUSB_ERROR_OTHER;
1648 /* And re-claim any interfaces which were claimed before the reset */
1649 for (i = 0; i < USB_MAXINTERFACES; i++) {
1650 if (handle->claimed_interfaces & (1L << i)) {
1652 * A driver may have completed modprobing during
1653 * IOCTL_USBFS_RESET, and bound itself as soon as
1654 * IOCTL_USBFS_RESET released the device lock
1656 r = detach_kernel_driver_and_claim(handle, i);
1658 usbi_warn(HANDLE_CTX(handle),
1659 "failed to re-claim interface %d after reset: %s",
1660 i, libusb_error_name(r));
1661 handle->claimed_interfaces &= ~(1L << i);
1662 ret = LIBUSB_ERROR_NOT_FOUND;
1667 usbi_mutex_unlock(&handle->lock);
1671 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1672 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1674 int r, fd = _device_handle_priv(handle)->fd;
1675 struct usbfs_streams *streams;
1677 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1678 return LIBUSB_ERROR_INVALID_PARAM;
1680 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1682 return LIBUSB_ERROR_NO_MEM;
1684 streams->num_streams = num_streams;
1685 streams->num_eps = num_endpoints;
1686 memcpy(streams->eps, endpoints, num_endpoints);
1688 r = ioctl(fd, req, streams);
1693 if (errno == ENOTTY)
1694 return LIBUSB_ERROR_NOT_SUPPORTED;
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 "streams-ioctl failed error %d errno %d", r, errno);
1702 return LIBUSB_ERROR_OTHER;
1707 static int op_alloc_streams(struct libusb_device_handle *handle,
1708 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1710 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1711 num_streams, endpoints, num_endpoints);
1714 static int op_free_streams(struct libusb_device_handle *handle,
1715 unsigned char *endpoints, int num_endpoints)
1717 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1718 endpoints, num_endpoints);
1721 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1724 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1725 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1726 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1727 if (buffer == MAP_FAILED) {
1728 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1735 static int op_dev_mem_free(struct libusb_device_handle *handle,
1736 unsigned char *buffer, size_t len)
1738 if (munmap(buffer, len) != 0) {
1739 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1741 return LIBUSB_ERROR_OTHER;
1743 return LIBUSB_SUCCESS;
1747 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1750 int fd = _device_handle_priv(handle)->fd;
1751 struct usbfs_getdriver getdrv;
1754 getdrv.interface = interface;
1755 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1757 if (errno == ENODATA)
1759 else if (errno == ENODEV)
1760 return LIBUSB_ERROR_NO_DEVICE;
1762 usbi_err(HANDLE_CTX(handle),
1763 "get driver failed error %d errno %d", r, errno);
1764 return LIBUSB_ERROR_OTHER;
1767 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1770 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1773 int fd = _device_handle_priv(handle)->fd;
1774 struct usbfs_ioctl command;
1775 struct usbfs_getdriver getdrv;
1778 command.ifno = interface;
1779 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1780 command.data = NULL;
1782 getdrv.interface = interface;
1783 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1784 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1785 return LIBUSB_ERROR_NOT_FOUND;
1787 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1789 if (errno == ENODATA)
1790 return LIBUSB_ERROR_NOT_FOUND;
1791 else if (errno == EINVAL)
1792 return LIBUSB_ERROR_INVALID_PARAM;
1793 else if (errno == ENODEV)
1794 return LIBUSB_ERROR_NO_DEVICE;
1796 usbi_err(HANDLE_CTX(handle),
1797 "detach failed error %d errno %d", r, errno);
1798 return LIBUSB_ERROR_OTHER;
1804 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1807 int fd = _device_handle_priv(handle)->fd;
1808 struct usbfs_ioctl command;
1811 command.ifno = interface;
1812 command.ioctl_code = IOCTL_USBFS_CONNECT;
1813 command.data = NULL;
1815 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1817 if (errno == ENODATA)
1818 return LIBUSB_ERROR_NOT_FOUND;
1819 else if (errno == EINVAL)
1820 return LIBUSB_ERROR_INVALID_PARAM;
1821 else if (errno == ENODEV)
1822 return LIBUSB_ERROR_NO_DEVICE;
1823 else if (errno == EBUSY)
1824 return LIBUSB_ERROR_BUSY;
1826 usbi_err(HANDLE_CTX(handle),
1827 "attach failed error %d errno %d", r, errno);
1828 return LIBUSB_ERROR_OTHER;
1829 } else if (r == 0) {
1830 return LIBUSB_ERROR_NOT_FOUND;
1836 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1839 struct usbfs_disconnect_claim dc;
1840 int r, fd = _device_handle_priv(handle)->fd;
1842 dc.interface = interface;
1843 strcpy(dc.driver, "usbfs");
1844 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1845 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1846 if (r != 0 && errno != ENOTTY) {
1849 return LIBUSB_ERROR_BUSY;
1851 return LIBUSB_ERROR_INVALID_PARAM;
1853 return LIBUSB_ERROR_NO_DEVICE;
1855 usbi_err(HANDLE_CTX(handle),
1856 "disconnect-and-claim failed errno %d", errno);
1857 return LIBUSB_ERROR_OTHER;
1861 /* Fallback code for kernels which don't support the
1862 disconnect-and-claim ioctl */
1863 r = op_detach_kernel_driver(handle, interface);
1864 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1867 return claim_interface(handle, interface);
1870 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1872 if (handle->auto_detach_kernel_driver)
1873 return detach_kernel_driver_and_claim(handle, iface);
1875 return claim_interface(handle, iface);
1878 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1882 r = release_interface(handle, iface);
1886 if (handle->auto_detach_kernel_driver)
1887 op_attach_kernel_driver(handle, iface);
1892 static void op_destroy_device(struct libusb_device *dev)
1894 struct linux_device_priv *priv = _device_priv(dev);
1895 if (priv->descriptors)
1896 free(priv->descriptors);
1897 if (priv->sysfs_dir)
1898 free(priv->sysfs_dir);
1901 /* URBs are discarded in reverse order of submission to avoid races. */
1902 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1904 struct libusb_transfer *transfer =
1905 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1906 struct linux_transfer_priv *tpriv =
1907 usbi_transfer_get_os_priv(itransfer);
1908 struct linux_device_handle_priv *dpriv =
1909 _device_handle_priv(transfer->dev_handle);
1911 struct usbfs_urb *urb;
1913 for (i = last_plus_one - 1; i >= first; i--) {
1914 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1915 urb = tpriv->iso_urbs[i];
1917 urb = &tpriv->urbs[i];
1919 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1922 if (EINVAL == errno) {
1923 usbi_dbg("URB not found --> assuming ready to be reaped");
1924 if (i == (last_plus_one - 1))
1925 ret = LIBUSB_ERROR_NOT_FOUND;
1926 } else if (ENODEV == errno) {
1927 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1928 ret = LIBUSB_ERROR_NO_DEVICE;
1930 usbi_warn(TRANSFER_CTX(transfer),
1931 "unrecognised discard errno %d", errno);
1932 ret = LIBUSB_ERROR_OTHER;
1938 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1941 for (i = 0; i < tpriv->num_urbs; i++) {
1942 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1948 free(tpriv->iso_urbs);
1949 tpriv->iso_urbs = NULL;
1952 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1954 struct libusb_transfer *transfer =
1955 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1956 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1957 struct linux_device_handle_priv *dpriv =
1958 _device_handle_priv(transfer->dev_handle);
1959 struct usbfs_urb *urbs;
1960 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1961 == LIBUSB_ENDPOINT_OUT;
1962 int bulk_buffer_len, use_bulk_continuation;
1966 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1967 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1968 return LIBUSB_ERROR_NOT_SUPPORTED;
1971 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1972 * around this by splitting large transfers into 16k blocks, and then
1973 * submit all urbs at once. it would be simpler to submit one urb at
1974 * a time, but there is a big performance gain doing it this way.
1976 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1977 * using arbritary large transfers can still be a bad idea though, as
1978 * the kernel needs to allocate physical contiguous memory for this,
1979 * which may fail for large buffers.
1981 * The kernel solves this problem by splitting the transfer into
1982 * blocks itself when the host-controller is scatter-gather capable
1983 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1985 * Last, there is the issue of short-transfers when splitting, for
1986 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1987 * is needed, but this is not always available.
1989 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1990 /* Good! Just submit everything in one go */
1991 bulk_buffer_len = transfer->length ? transfer->length : 1;
1992 use_bulk_continuation = 0;
1993 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1994 /* Split the transfers and use bulk-continuation to
1995 avoid issues with short-transfers */
1996 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1997 use_bulk_continuation = 1;
1998 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1999 /* Don't split, assume the kernel can alloc the buffer
2000 (otherwise the submit will fail with -ENOMEM) */
2001 bulk_buffer_len = transfer->length ? transfer->length : 1;
2002 use_bulk_continuation = 0;
2004 /* Bad, splitting without bulk-continuation, short transfers
2005 which end before the last urb will not work reliable! */
2006 /* Note we don't warn here as this is "normal" on kernels <
2007 2.6.32 and not a problem for most applications */
2008 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2009 use_bulk_continuation = 0;
2012 int num_urbs = transfer->length / bulk_buffer_len;
2013 int last_urb_partial = 0;
2015 if (transfer->length == 0) {
2017 } else if ((transfer->length % bulk_buffer_len) > 0) {
2018 last_urb_partial = 1;
2021 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2023 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2025 return LIBUSB_ERROR_NO_MEM;
2027 tpriv->num_urbs = num_urbs;
2028 tpriv->num_retired = 0;
2029 tpriv->reap_action = NORMAL;
2030 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2032 for (i = 0; i < num_urbs; i++) {
2033 struct usbfs_urb *urb = &urbs[i];
2034 urb->usercontext = itransfer;
2035 switch (transfer->type) {
2036 case LIBUSB_TRANSFER_TYPE_BULK:
2037 urb->type = USBFS_URB_TYPE_BULK;
2040 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2041 urb->type = USBFS_URB_TYPE_BULK;
2042 urb->stream_id = itransfer->stream_id;
2044 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2045 urb->type = USBFS_URB_TYPE_INTERRUPT;
2048 urb->endpoint = transfer->endpoint;
2049 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2050 /* don't set the short not ok flag for the last URB */
2051 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2052 urb->flags = USBFS_URB_SHORT_NOT_OK;
2053 if (i == num_urbs - 1 && last_urb_partial)
2054 urb->buffer_length = transfer->length % bulk_buffer_len;
2055 else if (transfer->length == 0)
2056 urb->buffer_length = 0;
2058 urb->buffer_length = bulk_buffer_len;
2060 if (i > 0 && use_bulk_continuation)
2061 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2063 /* we have already checked that the flag is supported */
2064 if (is_out && i == num_urbs - 1 &&
2065 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2066 urb->flags |= USBFS_URB_ZERO_PACKET;
2068 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2070 if (errno == ENODEV) {
2071 r = LIBUSB_ERROR_NO_DEVICE;
2073 usbi_err(TRANSFER_CTX(transfer),
2074 "submiturb failed error %d errno=%d", r, errno);
2075 r = LIBUSB_ERROR_IO;
2078 /* if the first URB submission fails, we can simply free up and
2079 * return failure immediately. */
2081 usbi_dbg("first URB failed, easy peasy");
2087 /* if it's not the first URB that failed, the situation is a bit
2088 * tricky. we may need to discard all previous URBs. there are
2090 * - discarding is asynchronous - discarded urbs will be reaped
2091 * later. the user must not have freed the transfer when the
2092 * discarded URBs are reaped, otherwise libusb will be using
2094 * - the earlier URBs may have completed successfully and we do
2095 * not want to throw away any data.
2096 * - this URB failing may be no error; EREMOTEIO means that
2097 * this transfer simply didn't need all the URBs we submitted
2098 * so, we report that the transfer was submitted successfully and
2099 * in case of error we discard all previous URBs. later when
2100 * the final reap completes we can report error to the user,
2101 * or success if an earlier URB was completed successfully.
2103 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2105 /* The URBs we haven't submitted yet we count as already
2107 tpriv->num_retired += num_urbs - i;
2109 /* If we completed short then don't try to discard. */
2110 if (COMPLETED_EARLY == tpriv->reap_action)
2113 discard_urbs(itransfer, 0, i);
2115 usbi_dbg("reporting successful submission but waiting for %d "
2116 "discards before reporting error", i);
2124 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2126 struct libusb_transfer *transfer =
2127 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2128 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2129 struct linux_device_handle_priv *dpriv =
2130 _device_handle_priv(transfer->dev_handle);
2131 struct usbfs_urb **urbs;
2132 int num_packets = transfer->num_iso_packets;
2133 int num_packets_remaining;
2136 unsigned int packet_len;
2137 unsigned int total_len = 0;
2138 unsigned char *urb_buffer = transfer->buffer;
2140 if (num_packets < 1)
2141 return LIBUSB_ERROR_INVALID_PARAM;
2143 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2144 * at least three times, but we attempt to detect this limit during
2145 * init and check it here. if the kernel rejects the request due to
2146 * its size, we return an error indicating such to the user.
2148 for (i = 0; i < num_packets; i++) {
2149 packet_len = transfer->iso_packet_desc[i].length;
2151 if (packet_len > max_iso_packet_len) {
2152 usbi_warn(TRANSFER_CTX(transfer),
2153 "iso packet length of %u bytes exceeds maximum of %u bytes",
2154 packet_len, max_iso_packet_len);
2155 return LIBUSB_ERROR_INVALID_PARAM;
2158 total_len += packet_len;
2161 if (transfer->length < (int)total_len)
2162 return LIBUSB_ERROR_INVALID_PARAM;
2164 /* usbfs limits the number of iso packets per URB */
2165 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2167 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2170 urbs = calloc(num_urbs, sizeof(*urbs));
2172 return LIBUSB_ERROR_NO_MEM;
2174 tpriv->iso_urbs = urbs;
2175 tpriv->num_urbs = num_urbs;
2176 tpriv->num_retired = 0;
2177 tpriv->reap_action = NORMAL;
2178 tpriv->iso_packet_offset = 0;
2180 /* allocate + initialize each URB with the correct number of packets */
2181 num_packets_remaining = num_packets;
2182 for (i = 0, j = 0; i < num_urbs; i++) {
2183 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2184 struct usbfs_urb *urb;
2188 alloc_size = sizeof(*urb)
2189 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2190 urb = calloc(1, alloc_size);
2192 free_iso_urbs(tpriv);
2193 return LIBUSB_ERROR_NO_MEM;
2197 /* populate packet lengths */
2198 for (k = 0; k < num_packets_in_urb; j++, k++) {
2199 packet_len = transfer->iso_packet_desc[j].length;
2200 urb->buffer_length += packet_len;
2201 urb->iso_frame_desc[k].length = packet_len;
2204 urb->usercontext = itransfer;
2205 urb->type = USBFS_URB_TYPE_ISO;
2206 /* FIXME: interface for non-ASAP data? */
2207 urb->flags = USBFS_URB_ISO_ASAP;
2208 urb->endpoint = transfer->endpoint;
2209 urb->number_of_packets = num_packets_in_urb;
2210 urb->buffer = urb_buffer;
2212 urb_buffer += urb->buffer_length;
2213 num_packets_remaining -= num_packets_in_urb;
2217 for (i = 0; i < num_urbs; i++) {
2218 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2220 if (errno == ENODEV) {
2221 r = LIBUSB_ERROR_NO_DEVICE;
2222 } else if (errno == EINVAL) {
2223 usbi_warn(TRANSFER_CTX(transfer),
2224 "submiturb failed, transfer too large");
2225 r = LIBUSB_ERROR_INVALID_PARAM;
2226 } else if (errno == EMSGSIZE) {
2227 usbi_warn(TRANSFER_CTX(transfer),
2228 "submiturb failed, iso packet length too large");
2229 r = LIBUSB_ERROR_INVALID_PARAM;
2231 usbi_err(TRANSFER_CTX(transfer),
2232 "submiturb failed error %d errno=%d", r, errno);
2233 r = LIBUSB_ERROR_IO;
2236 /* if the first URB submission fails, we can simply free up and
2237 * return failure immediately. */
2239 usbi_dbg("first URB failed, easy peasy");
2240 free_iso_urbs(tpriv);
2244 /* if it's not the first URB that failed, the situation is a bit
2245 * tricky. we must discard all previous URBs. there are
2247 * - discarding is asynchronous - discarded urbs will be reaped
2248 * later. the user must not have freed the transfer when the
2249 * discarded URBs are reaped, otherwise libusb will be using
2251 * - the earlier URBs may have completed successfully and we do
2252 * not want to throw away any data.
2253 * so, in this case we discard all the previous URBs BUT we report
2254 * that the transfer was submitted successfully. then later when
2255 * the final discard completes we can report error to the user.
2257 tpriv->reap_action = SUBMIT_FAILED;
2259 /* The URBs we haven't submitted yet we count as already
2261 tpriv->num_retired = num_urbs - i;
2262 discard_urbs(itransfer, 0, i);
2264 usbi_dbg("reporting successful submission but waiting for %d "
2265 "discards before reporting error", i);
2273 static int submit_control_transfer(struct usbi_transfer *itransfer)
2275 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2276 struct libusb_transfer *transfer =
2277 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2278 struct linux_device_handle_priv *dpriv =
2279 _device_handle_priv(transfer->dev_handle);
2280 struct usbfs_urb *urb;
2283 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2284 return LIBUSB_ERROR_INVALID_PARAM;
2286 urb = calloc(1, sizeof(struct usbfs_urb));
2288 return LIBUSB_ERROR_NO_MEM;
2290 tpriv->num_urbs = 1;
2291 tpriv->reap_action = NORMAL;
2293 urb->usercontext = itransfer;
2294 urb->type = USBFS_URB_TYPE_CONTROL;
2295 urb->endpoint = transfer->endpoint;
2296 urb->buffer = transfer->buffer;
2297 urb->buffer_length = transfer->length;
2299 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2303 if (errno == ENODEV)
2304 return LIBUSB_ERROR_NO_DEVICE;
2306 usbi_err(TRANSFER_CTX(transfer),
2307 "submiturb failed error %d errno=%d", r, errno);
2308 return LIBUSB_ERROR_IO;
2313 static int op_submit_transfer(struct usbi_transfer *itransfer)
2315 struct libusb_transfer *transfer =
2316 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2318 switch (transfer->type) {
2319 case LIBUSB_TRANSFER_TYPE_CONTROL:
2320 return submit_control_transfer(itransfer);
2321 case LIBUSB_TRANSFER_TYPE_BULK:
2322 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2323 return submit_bulk_transfer(itransfer);
2324 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2325 return submit_bulk_transfer(itransfer);
2326 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2327 return submit_iso_transfer(itransfer);
2329 usbi_err(TRANSFER_CTX(transfer),
2330 "unknown endpoint type %d", transfer->type);
2331 return LIBUSB_ERROR_INVALID_PARAM;
2335 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2337 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2338 struct libusb_transfer *transfer =
2339 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2343 return LIBUSB_ERROR_NOT_FOUND;
2345 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2349 switch (transfer->type) {
2350 case LIBUSB_TRANSFER_TYPE_BULK:
2351 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2352 if (tpriv->reap_action == ERROR)
2354 /* else, fall through */
2356 tpriv->reap_action = CANCELLED;
2362 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2364 struct libusb_transfer *transfer =
2365 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2366 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2368 switch (transfer->type) {
2369 case LIBUSB_TRANSFER_TYPE_CONTROL:
2370 case LIBUSB_TRANSFER_TYPE_BULK:
2371 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2372 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2378 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2379 if (tpriv->iso_urbs) {
2380 free_iso_urbs(tpriv);
2381 tpriv->iso_urbs = NULL;
2385 usbi_err(TRANSFER_CTX(transfer),
2386 "unknown endpoint type %d", transfer->type);
2390 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2391 struct usbfs_urb *urb)
2393 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2394 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2395 int urb_idx = urb - tpriv->urbs;
2397 usbi_mutex_lock(&itransfer->lock);
2398 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2399 urb_idx + 1, tpriv->num_urbs);
2401 tpriv->num_retired++;
2403 if (tpriv->reap_action != NORMAL) {
2404 /* cancelled, submit_fail, or completed early */
2405 usbi_dbg("abnormal reap: urb status %d", urb->status);
2407 /* even though we're in the process of cancelling, it's possible that
2408 * we may receive some data in these URBs that we don't want to lose.
2410 * 1. while the kernel is cancelling all the packets that make up an
2411 * URB, a few of them might complete. so we get back a successful
2412 * cancellation *and* some data.
2413 * 2. we receive a short URB which marks the early completion condition,
2414 * so we start cancelling the remaining URBs. however, we're too
2415 * slow and another URB completes (or at least completes partially).
2416 * (this can't happen since we always use BULK_CONTINUATION.)
2418 * When this happens, our objectives are not to lose any "surplus" data,
2419 * and also to stick it at the end of the previously-received data
2420 * (closing any holes), so that libusb reports the total amount of
2421 * transferred data and presents it in a contiguous chunk.
2423 if (urb->actual_length > 0) {
2424 unsigned char *target = transfer->buffer + itransfer->transferred;
2425 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2426 if (urb->buffer != target) {
2427 usbi_dbg("moving surplus data from offset %d to offset %d",
2428 (unsigned char *) urb->buffer - transfer->buffer,
2429 target - transfer->buffer);
2430 memmove(target, urb->buffer, urb->actual_length);
2432 itransfer->transferred += urb->actual_length;
2435 if (tpriv->num_retired == tpriv->num_urbs) {
2436 usbi_dbg("abnormal reap: last URB handled, reporting");
2437 if (tpriv->reap_action != COMPLETED_EARLY &&
2438 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2439 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2445 itransfer->transferred += urb->actual_length;
2447 /* Many of these errors can occur on *any* urb of a multi-urb
2448 * transfer. When they do, we tear down the rest of the transfer.
2450 switch (urb->status) {
2453 case -EREMOTEIO: /* short transfer */
2455 case -ENOENT: /* cancelled */
2460 usbi_dbg("device removed");
2461 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2462 goto cancel_remaining;
2464 usbi_dbg("detected endpoint stall");
2465 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2466 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2467 goto cancel_remaining;
2469 /* overflow can only ever occur in the last urb */
2470 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2471 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2472 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2479 usbi_dbg("low level error %d", urb->status);
2480 tpriv->reap_action = ERROR;
2481 goto cancel_remaining;
2483 usbi_warn(ITRANSFER_CTX(itransfer),
2484 "unrecognised urb status %d", urb->status);
2485 tpriv->reap_action = ERROR;
2486 goto cancel_remaining;
2489 /* if we're the last urb or we got less data than requested then we're
2491 if (urb_idx == tpriv->num_urbs - 1) {
2492 usbi_dbg("last URB in transfer --> complete!");
2494 } else if (urb->actual_length < urb->buffer_length) {
2495 usbi_dbg("short transfer %d/%d --> complete!",
2496 urb->actual_length, urb->buffer_length);
2497 if (tpriv->reap_action == NORMAL)
2498 tpriv->reap_action = COMPLETED_EARLY;
2503 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2504 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2506 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2509 /* cancel remaining urbs and wait for their completion before
2510 * reporting results */
2511 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2514 usbi_mutex_unlock(&itransfer->lock);
2520 usbi_mutex_unlock(&itransfer->lock);
2521 return CANCELLED == tpriv->reap_action ?
2522 usbi_handle_transfer_cancellation(itransfer) :
2523 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2526 static int handle_iso_completion(struct usbi_transfer *itransfer,
2527 struct usbfs_urb *urb)
2529 struct libusb_transfer *transfer =
2530 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2531 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2532 int num_urbs = tpriv->num_urbs;
2535 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2537 usbi_mutex_lock(&itransfer->lock);
2538 for (i = 0; i < num_urbs; i++) {
2539 if (urb == tpriv->iso_urbs[i]) {
2545 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2546 usbi_mutex_unlock(&itransfer->lock);
2547 return LIBUSB_ERROR_NOT_FOUND;
2550 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2553 /* copy isochronous results back in */
2555 for (i = 0; i < urb->number_of_packets; i++) {
2556 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2557 struct libusb_iso_packet_descriptor *lib_desc =
2558 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2559 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2560 switch (urb_desc->status) {
2563 case -ENOENT: /* cancelled */
2568 usbi_dbg("device removed");
2569 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2572 usbi_dbg("detected endpoint stall");
2573 lib_desc->status = LIBUSB_TRANSFER_STALL;
2576 usbi_dbg("overflow error");
2577 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2585 usbi_dbg("low-level USB error %d", urb_desc->status);
2586 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2589 usbi_warn(TRANSFER_CTX(transfer),
2590 "unrecognised urb status %d", urb_desc->status);
2591 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2594 lib_desc->actual_length = urb_desc->actual_length;
2597 tpriv->num_retired++;
2599 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2600 usbi_dbg("CANCEL: urb status %d", urb->status);
2602 if (tpriv->num_retired == num_urbs) {
2603 usbi_dbg("CANCEL: last URB handled, reporting");
2604 free_iso_urbs(tpriv);
2605 if (tpriv->reap_action == CANCELLED) {
2606 usbi_mutex_unlock(&itransfer->lock);
2607 return usbi_handle_transfer_cancellation(itransfer);
2609 usbi_mutex_unlock(&itransfer->lock);
2610 return usbi_handle_transfer_completion(itransfer,
2611 LIBUSB_TRANSFER_ERROR);
2617 switch (urb->status) {
2620 case -ENOENT: /* cancelled */
2624 usbi_dbg("device removed");
2625 status = LIBUSB_TRANSFER_NO_DEVICE;
2628 usbi_warn(TRANSFER_CTX(transfer),
2629 "unrecognised urb status %d", urb->status);
2630 status = LIBUSB_TRANSFER_ERROR;
2634 /* if we're the last urb then we're done */
2635 if (urb_idx == num_urbs) {
2636 usbi_dbg("last URB in transfer --> complete!");
2637 free_iso_urbs(tpriv);
2638 usbi_mutex_unlock(&itransfer->lock);
2639 return usbi_handle_transfer_completion(itransfer, status);
2643 usbi_mutex_unlock(&itransfer->lock);
2647 static int handle_control_completion(struct usbi_transfer *itransfer,
2648 struct usbfs_urb *urb)
2650 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2653 usbi_mutex_lock(&itransfer->lock);
2654 usbi_dbg("handling completion status %d", urb->status);
2656 itransfer->transferred += urb->actual_length;
2658 if (tpriv->reap_action == CANCELLED) {
2659 if (urb->status != 0 && urb->status != -ENOENT)
2660 usbi_warn(ITRANSFER_CTX(itransfer),
2661 "cancel: unrecognised urb status %d", urb->status);
2664 usbi_mutex_unlock(&itransfer->lock);
2665 return usbi_handle_transfer_cancellation(itransfer);
2668 switch (urb->status) {
2670 status = LIBUSB_TRANSFER_COMPLETED;
2672 case -ENOENT: /* cancelled */
2673 status = LIBUSB_TRANSFER_CANCELLED;
2677 usbi_dbg("device removed");
2678 status = LIBUSB_TRANSFER_NO_DEVICE;
2681 usbi_dbg("unsupported control request");
2682 status = LIBUSB_TRANSFER_STALL;
2685 usbi_dbg("control overflow error");
2686 status = LIBUSB_TRANSFER_OVERFLOW;
2693 usbi_dbg("low-level bus error occurred");
2694 status = LIBUSB_TRANSFER_ERROR;
2697 usbi_warn(ITRANSFER_CTX(itransfer),
2698 "unrecognised urb status %d", urb->status);
2699 status = LIBUSB_TRANSFER_ERROR;
2705 usbi_mutex_unlock(&itransfer->lock);
2706 return usbi_handle_transfer_completion(itransfer, status);
2709 static int reap_for_handle(struct libusb_device_handle *handle)
2711 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2713 struct usbfs_urb *urb;
2714 struct usbi_transfer *itransfer;
2715 struct libusb_transfer *transfer;
2717 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2718 if (r == -1 && errno == EAGAIN)
2721 if (errno == ENODEV)
2722 return LIBUSB_ERROR_NO_DEVICE;
2724 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2726 return LIBUSB_ERROR_IO;
2729 itransfer = urb->usercontext;
2730 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2732 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2733 urb->actual_length);
2735 switch (transfer->type) {
2736 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2737 return handle_iso_completion(itransfer, urb);
2738 case LIBUSB_TRANSFER_TYPE_BULK:
2739 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2740 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2741 return handle_bulk_completion(itransfer, urb);
2742 case LIBUSB_TRANSFER_TYPE_CONTROL:
2743 return handle_control_completion(itransfer, urb);
2745 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2747 return LIBUSB_ERROR_OTHER;
2751 static int op_handle_events(struct libusb_context *ctx,
2752 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2757 usbi_mutex_lock(&ctx->open_devs_lock);
2758 for (i = 0; i < nfds && num_ready > 0; i++) {
2759 struct pollfd *pollfd = &fds[i];
2760 struct libusb_device_handle *handle;
2761 struct linux_device_handle_priv *hpriv = NULL;
2763 if (!pollfd->revents)
2767 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2768 hpriv = _device_handle_priv(handle);
2769 if (hpriv->fd == pollfd->fd)
2773 if (!hpriv || hpriv->fd != pollfd->fd) {
2774 usbi_err(ctx, "cannot find handle for fd %d",
2779 if (pollfd->revents & POLLERR) {
2780 /* remove the fd from the pollfd set so that it doesn't continuously
2781 * trigger an event, and flag that it has been removed so op_close()
2782 * doesn't try to remove it a second time */
2783 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2784 hpriv->fd_removed = 1;
2786 /* device will still be marked as attached if hotplug monitor thread
2787 * hasn't processed remove event yet */
2788 usbi_mutex_static_lock(&linux_hotplug_lock);
2789 if (handle->dev->attached)
2790 linux_device_disconnected(handle->dev->bus_number,
2791 handle->dev->device_address);
2792 usbi_mutex_static_unlock(&linux_hotplug_lock);
2794 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2796 r = reap_for_handle(handle);
2800 usbi_handle_disconnect(handle);
2805 r = reap_for_handle(handle);
2807 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2815 usbi_mutex_unlock(&ctx->open_devs_lock);
2819 static int op_clock_gettime(int clk_id, struct timespec *tp)
2822 case USBI_CLOCK_MONOTONIC:
2823 return clock_gettime(monotonic_clkid, tp);
2824 case USBI_CLOCK_REALTIME:
2825 return clock_gettime(CLOCK_REALTIME, tp);
2827 return LIBUSB_ERROR_INVALID_PARAM;
2831 #ifdef USBI_TIMERFD_AVAILABLE
2832 static clockid_t op_get_timerfd_clockid(void)
2834 return monotonic_clkid;
2839 const struct usbi_os_backend usbi_backend = {
2840 .name = "Linux usbfs",
2841 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2844 .get_device_list = NULL,
2845 .hotplug_poll = op_hotplug_poll,
2846 .get_device_descriptor = op_get_device_descriptor,
2847 .get_active_config_descriptor = op_get_active_config_descriptor,
2848 .get_config_descriptor = op_get_config_descriptor,
2849 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2851 .wrap_sys_device = op_wrap_sys_device,
2854 .get_configuration = op_get_configuration,
2855 .set_configuration = op_set_configuration,
2856 .claim_interface = op_claim_interface,
2857 .release_interface = op_release_interface,
2859 .set_interface_altsetting = op_set_interface,
2860 .clear_halt = op_clear_halt,
2861 .reset_device = op_reset_device,
2863 .alloc_streams = op_alloc_streams,
2864 .free_streams = op_free_streams,
2866 .dev_mem_alloc = op_dev_mem_alloc,
2867 .dev_mem_free = op_dev_mem_free,
2869 .kernel_driver_active = op_kernel_driver_active,
2870 .detach_kernel_driver = op_detach_kernel_driver,
2871 .attach_kernel_driver = op_attach_kernel_driver,
2873 .destroy_device = op_destroy_device,
2875 .submit_transfer = op_submit_transfer,
2876 .cancel_transfer = op_cancel_transfer,
2877 .clear_transfer_priv = op_clear_transfer_priv,
2879 .handle_events = op_handle_events,
2881 .clock_gettime = op_clock_gettime,
2883 #ifdef USBI_TIMERFD_AVAILABLE
2884 .get_timerfd_clockid = op_get_timerfd_clockid,
2887 .device_priv_size = sizeof(struct linux_device_priv),
2888 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2889 .transfer_priv_size = sizeof(struct linux_transfer_priv),