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 {
173 /* submission failed after the first URB, so await cancellation/completion
174 * of all the others */
177 /* cancelled by user or timeout */
180 /* completed multi-URB transfer in non-final URB */
183 /* one or more urbs encountered a low-level error */
187 struct linux_transfer_priv {
189 struct usbfs_urb *urbs;
190 struct usbfs_urb **iso_urbs;
193 enum reap_action reap_action;
196 enum libusb_transfer_status reap_status;
198 /* next iso packet in user-supplied transfer to be populated */
199 int iso_packet_offset;
202 static int _open(const char *path, int flags)
204 #if defined(O_CLOEXEC)
205 if (supports_flag_cloexec)
206 return open(path, flags | O_CLOEXEC);
209 return open(path, flags);
212 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
214 struct libusb_context *ctx = DEVICE_CTX(dev);
220 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
221 usbfs_path, dev->bus_number, dev->device_address);
223 snprintf(path, PATH_MAX, "%s/%03d/%03d",
224 usbfs_path, dev->bus_number, dev->device_address);
226 fd = _open(path, mode);
228 return fd; /* Success */
230 if (errno == ENOENT) {
232 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
234 /* Wait 10ms for USB device path creation.*/
235 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
237 fd = _open(path, mode);
239 return fd; /* Success */
243 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
244 path, strerror(errno));
245 if (errno == EACCES && mode == O_RDWR)
246 usbi_err(ctx, "libusb requires write access to USB "
251 return LIBUSB_ERROR_ACCESS;
253 return LIBUSB_ERROR_NO_DEVICE;
254 return LIBUSB_ERROR_IO;
257 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
259 return (struct linux_device_priv *) dev->os_priv;
262 static struct linux_device_handle_priv *_device_handle_priv(
263 struct libusb_device_handle *handle)
265 return (struct linux_device_handle_priv *) handle->os_priv;
268 /* check dirent for a /dev/usbdev%d.%d name
269 * optionally return bus/device on success */
270 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
274 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
277 usbi_dbg("found: %s", entry->d_name);
285 static int check_usb_vfs(const char *dirname)
288 struct dirent *entry;
291 dir = opendir(dirname);
295 while ((entry = readdir(dir)) != NULL) {
296 if (entry->d_name[0] == '.')
299 /* We assume if we find any files that it must be the right place */
308 static const char *find_usbfs_path(void)
310 const char *path = "/dev/bus/usb";
311 const char *ret = NULL;
313 if (check_usb_vfs(path)) {
316 path = "/proc/bus/usb";
317 if (check_usb_vfs(path))
321 /* look for /dev/usbdev*.* if the normal places fail */
323 struct dirent *entry;
329 while ((entry = readdir(dir)) != NULL) {
330 if (_is_usbdev_entry(entry, NULL, NULL)) {
331 /* found one; that's enough */
341 /* On udev based systems without any usb-devices /dev/bus/usb will not
342 * exist. So if we've not found anything and we're using udev for hotplug
343 * simply assume /dev/bus/usb rather then making libusb_init fail. */
344 #if defined(USE_UDEV)
346 ret = "/dev/bus/usb";
350 usbi_dbg("found usbfs at %s", ret);
355 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
356 * seem to lack it). fall back to REALTIME if we have to. */
357 static clockid_t find_monotonic_clock(void)
359 #ifdef CLOCK_MONOTONIC
363 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
364 * because it's not available through timerfd */
365 r = clock_gettime(CLOCK_MONOTONIC, &ts);
367 return CLOCK_MONOTONIC;
368 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
371 return CLOCK_REALTIME;
374 static int get_kernel_version(struct libusb_context *ctx,
375 struct kernel_version *ver)
380 if (uname(&uts) < 0) {
381 usbi_err(ctx, "uname failed, errno %d", errno);
385 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
387 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
396 usbi_dbg("reported kernel version is %s", uts.release);
401 static int kernel_version_ge(const struct kernel_version *ver,
402 int major, int minor, int sublevel)
404 if (ver->major > major)
406 else if (ver->major < major)
409 /* kmajor == major */
410 if (ver->minor == -1 && ver->sublevel == -1)
411 return 0 == minor && 0 == sublevel;
412 else if (ver->minor > minor)
414 else if (ver->minor < minor)
417 /* kminor == minor */
418 if (ver->sublevel == -1)
419 return 0 == sublevel;
421 return ver->sublevel >= sublevel;
424 static int op_init(struct libusb_context *ctx)
426 struct kernel_version kversion;
430 usbfs_path = find_usbfs_path();
432 usbi_err(ctx, "could not find usbfs");
433 return LIBUSB_ERROR_OTHER;
436 if (monotonic_clkid == -1)
437 monotonic_clkid = find_monotonic_clock();
439 if (get_kernel_version(ctx, &kversion) < 0)
440 return LIBUSB_ERROR_OTHER;
442 if (supports_flag_cloexec == -1) {
443 /* O_CLOEXEC flag available from Linux 2.6.23 */
444 supports_flag_cloexec = kernel_version_ge(&kversion,2,6,23);
447 if (supports_flag_bulk_continuation == -1) {
448 /* bulk continuation URB flag available from Linux 2.6.32 */
449 supports_flag_bulk_continuation = kernel_version_ge(&kversion,2,6,32);
452 if (supports_flag_bulk_continuation)
453 usbi_dbg("bulk continuation flag supported");
455 if (-1 == supports_flag_zero_packet) {
456 /* zero length packet URB flag fixed since Linux 2.6.31 */
457 supports_flag_zero_packet = kernel_version_ge(&kversion,2,6,31);
460 if (supports_flag_zero_packet)
461 usbi_dbg("zero length packet flag supported");
463 if (!max_iso_packet_len) {
464 if (kernel_version_ge(&kversion,3,10,0))
465 max_iso_packet_len = 49152;
466 else if (kernel_version_ge(&kversion,2,6,18))
467 max_iso_packet_len = 8192;
469 max_iso_packet_len = 1023;
472 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
474 if (-1 == sysfs_has_descriptors) {
475 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
476 sysfs_has_descriptors = kernel_version_ge(&kversion,2,6,26);
479 if (-1 == sysfs_can_relate_devices) {
480 /* sysfs has busnum since Linux 2.6.22 */
481 sysfs_can_relate_devices = kernel_version_ge(&kversion,2,6,22);
484 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
485 r = stat(SYSFS_DEVICE_PATH, &statbuf);
486 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
487 usbi_warn(ctx, "sysfs not mounted");
488 sysfs_can_relate_devices = 0;
489 sysfs_has_descriptors = 0;
493 if (sysfs_can_relate_devices)
494 usbi_dbg("sysfs can relate devices");
496 if (sysfs_has_descriptors)
497 usbi_dbg("sysfs has complete descriptors");
499 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
501 if (init_count == 0) {
502 /* start up hotplug event handler */
503 r = linux_start_event_monitor();
505 if (r == LIBUSB_SUCCESS) {
506 r = linux_scan_devices(ctx);
507 if (r == LIBUSB_SUCCESS)
509 else if (init_count == 0)
510 linux_stop_event_monitor();
512 usbi_err(ctx, "error starting hotplug event monitor");
513 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
518 static void op_exit(struct libusb_context *ctx)
521 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
522 assert(init_count != 0);
524 /* tear down event handler */
525 (void)linux_stop_event_monitor();
527 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
530 static int linux_start_event_monitor(void)
532 #if defined(USE_UDEV)
533 return linux_udev_start_event_monitor();
535 return linux_netlink_start_event_monitor();
539 static int linux_stop_event_monitor(void)
541 #if defined(USE_UDEV)
542 return linux_udev_stop_event_monitor();
544 return linux_netlink_stop_event_monitor();
548 static int linux_scan_devices(struct libusb_context *ctx)
552 usbi_mutex_static_lock(&linux_hotplug_lock);
554 #if defined(USE_UDEV)
555 ret = linux_udev_scan_devices(ctx);
557 ret = linux_default_scan_devices(ctx);
560 usbi_mutex_static_unlock(&linux_hotplug_lock);
565 static void op_hotplug_poll(void)
567 #if defined(USE_UDEV)
568 linux_udev_hotplug_poll();
570 linux_netlink_hotplug_poll();
574 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
576 struct linux_device_priv *priv = _device_priv(dev);
577 char filename[PATH_MAX];
580 snprintf(filename, PATH_MAX, "%s/%s/%s",
581 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
582 fd = _open(filename, O_RDONLY);
584 usbi_err(DEVICE_CTX(dev),
585 "open %s failed ret=%d errno=%d", filename, fd, errno);
586 return LIBUSB_ERROR_IO;
592 /* Note only suitable for attributes which always read >= 0, < 0 is error */
593 static int __read_sysfs_attr(struct libusb_context *ctx,
594 const char *devname, const char *attr)
596 char filename[PATH_MAX];
600 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
602 fd = _open(filename, O_RDONLY);
604 if (errno == ENOENT) {
605 /* File doesn't exist. Assume the device has been
606 disconnected (see trac ticket #70). */
607 return LIBUSB_ERROR_NO_DEVICE;
609 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
610 return LIBUSB_ERROR_IO;
615 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
617 return LIBUSB_ERROR_OTHER;
620 r = fscanf(f, "%d", &value);
623 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
624 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
627 usbi_err(ctx, "%s contains a negative value", filename);
628 return LIBUSB_ERROR_IO;
634 static int op_get_device_descriptor(struct libusb_device *dev,
635 unsigned char *buffer, int *host_endian)
637 struct linux_device_priv *priv = _device_priv(dev);
639 *host_endian = (priv->sysfs_dir && sysfs_has_descriptors) ? 0 : 1;
640 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
645 /* read the bConfigurationValue for a device */
646 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
649 char tmp[5] = {0, 0, 0, 0, 0};
654 fd = _open_sysfs_attr(dev, "bConfigurationValue");
658 r = read(fd, tmp, sizeof(tmp));
661 usbi_err(DEVICE_CTX(dev),
662 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
663 return LIBUSB_ERROR_IO;
665 usbi_dbg("device unconfigured");
670 if (tmp[sizeof(tmp) - 1] != 0) {
671 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
672 return LIBUSB_ERROR_IO;
673 } else if (tmp[0] == 0) {
674 usbi_err(DEVICE_CTX(dev), "no configuration value?");
675 return LIBUSB_ERROR_IO;
678 num = strtol(tmp, &endptr, 10);
680 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
681 return LIBUSB_ERROR_IO;
688 int linux_get_device_address (struct libusb_context *ctx, int detached,
689 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
690 const char *sys_name, int fd)
692 char proc_path[PATH_MAX], fd_path[PATH_MAX];
696 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
697 /* can't use sysfs to read the bus and device number if the
698 * device has been detached */
699 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
700 if (NULL == dev_node && fd >= 0) {
701 /* try to retrieve the device node from fd */
702 snprintf(proc_path, PATH_MAX, "/proc/self/fd/%d", fd);
703 r = readlink(proc_path, fd_path, PATH_MAX);
707 if (NULL == dev_node) {
708 return LIBUSB_ERROR_OTHER;
711 /* will this work with all supported kernel versions? */
712 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
713 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
714 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
715 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
717 return LIBUSB_ERROR_OTHER;
720 return LIBUSB_SUCCESS;
723 usbi_dbg("scan %s", sys_name);
725 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
728 if (sysfs_attr > 255)
729 return LIBUSB_ERROR_INVALID_PARAM;
730 *busnum = (uint8_t) sysfs_attr;
732 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
735 if (sysfs_attr > 255)
736 return LIBUSB_ERROR_INVALID_PARAM;
738 *devaddr = (uint8_t) sysfs_attr;
740 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
742 return LIBUSB_SUCCESS;
745 /* Return offset of the next descriptor with the given type */
746 static int seek_to_next_descriptor(struct libusb_context *ctx,
747 uint8_t descriptor_type, unsigned char *buffer, int size)
749 struct usb_descriptor_header header;
752 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
754 return LIBUSB_ERROR_NOT_FOUND;
757 usbi_err(ctx, "short descriptor read %d/2", size);
758 return LIBUSB_ERROR_IO;
760 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
762 if (i && header.bDescriptorType == descriptor_type)
765 usbi_err(ctx, "bLength overflow by %d bytes", -size);
766 return LIBUSB_ERROR_IO;
769 /* Return offset to next config */
770 static int seek_to_next_config(struct libusb_device *dev,
771 unsigned char *buffer, int size)
773 struct libusb_context *ctx = DEVICE_CTX(dev);
774 struct linux_device_priv *priv = _device_priv(dev);
775 struct libusb_config_descriptor config;
778 return LIBUSB_ERROR_NOT_FOUND;
780 if (size < LIBUSB_DT_CONFIG_SIZE) {
781 usbi_err(ctx, "short descriptor read %d/%d",
782 size, LIBUSB_DT_CONFIG_SIZE);
783 return LIBUSB_ERROR_IO;
786 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
787 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
788 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
789 config.bDescriptorType);
790 return LIBUSB_ERROR_IO;
794 * In usbfs the config descriptors are config.wTotalLength bytes apart,
795 * with any short reads from the device appearing as holes in the file.
797 * In sysfs wTotalLength is ignored, instead the kernel returns a
798 * config descriptor with verified bLength fields, with descriptors
799 * with an invalid bLength removed.
801 if (priv->sysfs_dir && sysfs_has_descriptors) {
802 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
804 if (next == LIBUSB_ERROR_NOT_FOUND)
809 if (next != config.wTotalLength)
810 usbi_warn(ctx, "config length mismatch wTotalLength "
811 "%d real %d", config.wTotalLength, next);
814 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
815 usbi_err(ctx, "invalid wTotalLength %d",
816 config.wTotalLength);
817 return LIBUSB_ERROR_IO;
818 } else if (config.wTotalLength > size) {
819 usbi_warn(ctx, "short descriptor read %d/%d",
820 size, config.wTotalLength);
823 return config.wTotalLength;
827 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
828 uint8_t value, unsigned char **buffer, int *host_endian)
830 struct linux_device_priv *priv = _device_priv(dev);
831 unsigned char *descriptors = priv->descriptors;
832 int size = priv->descriptors_len;
833 struct libusb_config_descriptor *config;
836 /* Unlike the device desc. config descs. are always in raw format */
839 /* Skip device header */
840 descriptors += DEVICE_DESC_LENGTH;
841 size -= DEVICE_DESC_LENGTH;
843 /* Seek till the config is found, or till "EOF" */
845 int next = seek_to_next_config(dev, descriptors, size);
848 config = (struct libusb_config_descriptor *)descriptors;
849 if (config->bConfigurationValue == value) {
850 *buffer = descriptors;
858 static int op_get_active_config_descriptor(struct libusb_device *dev,
859 unsigned char *buffer, size_t len, int *host_endian)
861 struct linux_device_priv *priv = _device_priv(dev);
863 unsigned char *config_desc;
865 if (priv->sysfs_dir && sysfs_can_relate_devices) {
866 r = sysfs_get_active_config(dev, &config);
870 /* Use cached bConfigurationValue */
871 config = priv->active_config;
874 return LIBUSB_ERROR_NOT_FOUND;
876 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
881 len = MIN(len, (size_t)r);
882 memcpy(buffer, config_desc, len);
886 static int op_get_config_descriptor(struct libusb_device *dev,
887 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
889 struct linux_device_priv *priv = _device_priv(dev);
890 unsigned char *descriptors = priv->descriptors;
891 int i, r, size = priv->descriptors_len;
893 /* Unlike the device desc. config descs. are always in raw format */
896 /* Skip device header */
897 descriptors += DEVICE_DESC_LENGTH;
898 size -= DEVICE_DESC_LENGTH;
900 /* Seek till the config is found, or till "EOF" */
902 r = seek_to_next_config(dev, descriptors, size);
905 if (i == config_index)
911 len = MIN(len, (size_t)r);
912 memcpy(buffer, descriptors, len);
916 /* send a control message to retrieve active configuration */
917 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
919 struct linux_device_priv *priv = _device_priv(dev);
920 unsigned char active_config = 0;
923 struct usbfs_ctrltransfer ctrl = {
924 .bmRequestType = LIBUSB_ENDPOINT_IN,
925 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
930 .data = &active_config
933 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
936 return LIBUSB_ERROR_NO_DEVICE;
938 /* we hit this error path frequently with buggy devices :( */
939 usbi_warn(DEVICE_CTX(dev),
940 "get_configuration failed ret=%d errno=%d", r, errno);
941 priv->active_config = -1;
943 if (active_config > 0) {
944 priv->active_config = active_config;
946 /* some buggy devices have a configuration 0, but we're
947 * reaching into the corner of a corner case here, so let's
948 * not support buggy devices in these circumstances.
949 * stick to the specs: a configuration value of 0 means
951 usbi_warn(DEVICE_CTX(dev),
952 "active cfg 0? assuming unconfigured device");
953 priv->active_config = -1;
957 return LIBUSB_SUCCESS;
960 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
961 uint8_t devaddr, const char *sysfs_dir)
963 struct linux_device_priv *priv = _device_priv(dev);
964 struct libusb_context *ctx = DEVICE_CTX(dev);
965 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
969 dev->bus_number = busnum;
970 dev->device_address = devaddr;
973 priv->sysfs_dir = strdup(sysfs_dir);
974 if (!priv->sysfs_dir)
975 return LIBUSB_ERROR_NO_MEM;
977 /* Note speed can contain 1.5, in this case __read_sysfs_attr
978 will stop parsing at the '.' and return 1 */
979 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
982 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
983 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
984 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
985 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
986 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
988 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
993 /* cache descriptors in memory */
994 if (sysfs_dir && sysfs_has_descriptors)
995 fd = _open_sysfs_attr(dev, "descriptors");
997 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1002 descriptors_size *= 2;
1003 priv->descriptors = usbi_reallocf(priv->descriptors,
1005 if (!priv->descriptors) {
1007 return LIBUSB_ERROR_NO_MEM;
1009 /* usbfs has holes in the file */
1010 if (!(sysfs_dir && sysfs_has_descriptors)) {
1011 memset(priv->descriptors + priv->descriptors_len,
1012 0, descriptors_size - priv->descriptors_len);
1014 r = read(fd, priv->descriptors + priv->descriptors_len,
1015 descriptors_size - priv->descriptors_len);
1017 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1020 return LIBUSB_ERROR_IO;
1022 priv->descriptors_len += r;
1023 } while (priv->descriptors_len == descriptors_size);
1027 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1028 usbi_err(ctx, "short descriptor read (%d)",
1029 priv->descriptors_len);
1030 return LIBUSB_ERROR_IO;
1033 if (sysfs_dir && sysfs_can_relate_devices)
1034 return LIBUSB_SUCCESS;
1036 /* cache active config */
1037 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1039 /* cannot send a control message to determine the active
1040 * config. just assume the first one is active. */
1041 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1042 "active configuration descriptor");
1043 if (priv->descriptors_len >=
1044 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1045 struct libusb_config_descriptor config;
1046 usbi_parse_descriptor(
1047 priv->descriptors + DEVICE_DESC_LENGTH,
1048 "bbwbbbbb", &config, 0);
1049 priv->active_config = config.bConfigurationValue;
1051 priv->active_config = -1; /* No config dt */
1053 return LIBUSB_SUCCESS;
1056 r = usbfs_get_active_config(dev, fd);
1062 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1064 struct libusb_context *ctx = DEVICE_CTX(dev);
1065 struct libusb_device *it;
1066 char *parent_sysfs_dir, *tmp;
1067 int ret, add_parent = 1;
1069 /* XXX -- can we figure out the topology when using usbfs? */
1070 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1071 /* either using usbfs or finding the parent of a root hub */
1072 return LIBUSB_SUCCESS;
1075 parent_sysfs_dir = strdup(sysfs_dir);
1076 if (NULL == parent_sysfs_dir) {
1077 return LIBUSB_ERROR_NO_MEM;
1079 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1080 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1081 dev->port_number = atoi(tmp + 1);
1084 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1086 free (parent_sysfs_dir);
1087 return LIBUSB_SUCCESS;
1090 /* is the parent a root hub? */
1091 if (NULL == strchr(parent_sysfs_dir, '-')) {
1092 tmp = parent_sysfs_dir;
1093 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1096 return LIBUSB_ERROR_NO_MEM;
1101 /* find the parent in the context */
1102 usbi_mutex_lock(&ctx->usb_devs_lock);
1103 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1104 struct linux_device_priv *priv = _device_priv(it);
1105 if (priv->sysfs_dir) {
1106 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1107 dev->parent_dev = libusb_ref_device(it);
1112 usbi_mutex_unlock(&ctx->usb_devs_lock);
1114 if (!dev->parent_dev && add_parent) {
1115 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1117 sysfs_scan_device(ctx, parent_sysfs_dir);
1122 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1123 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1125 free (parent_sysfs_dir);
1127 return LIBUSB_SUCCESS;
1130 int linux_enumerate_device(struct libusb_context *ctx,
1131 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1133 unsigned long session_id;
1134 struct libusb_device *dev;
1137 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1138 * will be reused. instead we should add a simple sysfs attribute with
1140 session_id = busnum << 8 | devaddr;
1141 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1144 dev = usbi_get_device_by_session_id(ctx, session_id);
1146 /* device already exists in the context */
1147 usbi_dbg("session_id %ld already exists", session_id);
1148 libusb_unref_device(dev);
1149 return LIBUSB_SUCCESS;
1152 usbi_dbg("allocating new device for %d/%d (session %ld)",
1153 busnum, devaddr, session_id);
1154 dev = usbi_alloc_device(ctx, session_id);
1156 return LIBUSB_ERROR_NO_MEM;
1158 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1161 r = usbi_sanitize_device(dev);
1165 r = linux_get_parent_info(dev, sysfs_dir);
1170 libusb_unref_device(dev);
1172 usbi_connect_device(dev);
1177 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1179 struct libusb_context *ctx;
1181 usbi_mutex_static_lock(&active_contexts_lock);
1182 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1183 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1185 usbi_mutex_static_unlock(&active_contexts_lock);
1188 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1190 struct libusb_context *ctx;
1191 struct libusb_device *dev;
1192 unsigned long session_id = busnum << 8 | devaddr;
1194 usbi_mutex_static_lock(&active_contexts_lock);
1195 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1196 dev = usbi_get_device_by_session_id (ctx, session_id);
1198 usbi_disconnect_device (dev);
1199 libusb_unref_device(dev);
1201 usbi_dbg("device not found for session %x", session_id);
1204 usbi_mutex_static_unlock(&active_contexts_lock);
1207 #if !defined(USE_UDEV)
1208 /* open a bus directory and adds all discovered devices to the context */
1209 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1212 char dirpath[PATH_MAX];
1213 struct dirent *entry;
1214 int r = LIBUSB_ERROR_IO;
1216 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1217 usbi_dbg("%s", dirpath);
1218 dir = opendir(dirpath);
1220 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1221 /* FIXME: should handle valid race conditions like hub unplugged
1222 * during directory iteration - this is not an error */
1226 while ((entry = readdir(dir))) {
1229 if (entry->d_name[0] == '.')
1232 devaddr = atoi(entry->d_name);
1234 usbi_dbg("unknown dir entry %s", entry->d_name);
1238 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1239 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1250 static int usbfs_get_device_list(struct libusb_context *ctx)
1252 struct dirent *entry;
1253 DIR *buses = opendir(usbfs_path);
1257 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1258 return LIBUSB_ERROR_IO;
1261 while ((entry = readdir(buses))) {
1264 if (entry->d_name[0] == '.')
1269 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1272 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1274 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1278 busnum = atoi(entry->d_name);
1280 usbi_dbg("unknown dir entry %s", entry->d_name);
1284 r = usbfs_scan_busdir(ctx, busnum);
1296 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1298 uint8_t busnum, devaddr;
1301 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname, -1);
1302 if (LIBUSB_SUCCESS != ret) {
1306 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1310 #if !defined(USE_UDEV)
1311 static int sysfs_get_device_list(struct libusb_context *ctx)
1313 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1314 struct dirent *entry;
1315 int num_devices = 0;
1316 int num_enumerated = 0;
1319 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1320 return LIBUSB_ERROR_IO;
1323 while ((entry = readdir(devices))) {
1324 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1325 || strchr(entry->d_name, ':'))
1330 if (sysfs_scan_device(ctx, entry->d_name)) {
1331 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1340 /* successful if at least one device was enumerated or no devices were found */
1341 if (num_enumerated || !num_devices)
1342 return LIBUSB_SUCCESS;
1344 return LIBUSB_ERROR_IO;
1347 static int linux_default_scan_devices (struct libusb_context *ctx)
1349 /* we can retrieve device list and descriptors from sysfs or usbfs.
1350 * sysfs is preferable, because if we use usbfs we end up resuming
1351 * any autosuspended USB devices. however, sysfs is not available
1352 * everywhere, so we need a usbfs fallback too.
1354 * as described in the "sysfs vs usbfs" comment at the top of this
1355 * file, sometimes we have sysfs but not enough information to
1356 * relate sysfs devices to usbfs nodes. op_init() determines the
1357 * adequacy of sysfs and sets sysfs_can_relate_devices.
1359 if (sysfs_can_relate_devices != 0)
1360 return sysfs_get_device_list(ctx);
1362 return usbfs_get_device_list(ctx);
1366 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1368 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1373 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1375 if (errno == ENOTTY)
1376 usbi_dbg("getcap not available");
1378 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1380 if (supports_flag_zero_packet)
1381 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1382 if (supports_flag_bulk_continuation)
1383 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1386 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1389 static int op_open(struct libusb_device_handle *handle)
1391 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1394 fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1396 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1397 /* device will still be marked as attached if hotplug monitor thread
1398 * hasn't processed remove event yet */
1399 usbi_mutex_static_lock(&linux_hotplug_lock);
1400 if (handle->dev->attached) {
1401 usbi_dbg("open failed with no device, but device still attached");
1402 linux_device_disconnected(handle->dev->bus_number,
1403 handle->dev->device_address);
1405 usbi_mutex_static_unlock(&linux_hotplug_lock);
1410 r = initialize_handle(handle, fd);
1417 static void op_close(struct libusb_device_handle *dev_handle)
1419 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1420 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1421 if (!hpriv->fd_removed)
1422 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1426 static int op_get_configuration(struct libusb_device_handle *handle,
1429 struct linux_device_priv *priv = _device_priv(handle->dev);
1432 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1433 r = sysfs_get_active_config(handle->dev, config);
1435 r = usbfs_get_active_config(handle->dev,
1436 _device_handle_priv(handle)->fd);
1437 if (r == LIBUSB_SUCCESS)
1438 *config = priv->active_config;
1443 if (*config == -1) {
1444 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1451 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1453 struct linux_device_priv *priv = _device_priv(handle->dev);
1454 int fd = _device_handle_priv(handle)->fd;
1455 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1457 if (errno == EINVAL)
1458 return LIBUSB_ERROR_NOT_FOUND;
1459 else if (errno == EBUSY)
1460 return LIBUSB_ERROR_BUSY;
1461 else if (errno == ENODEV)
1462 return LIBUSB_ERROR_NO_DEVICE;
1464 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1465 return LIBUSB_ERROR_OTHER;
1468 /* update our cached active config descriptor */
1469 priv->active_config = config;
1471 return LIBUSB_SUCCESS;
1474 static int claim_interface(struct libusb_device_handle *handle, int iface)
1476 int fd = _device_handle_priv(handle)->fd;
1477 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1479 if (errno == ENOENT)
1480 return LIBUSB_ERROR_NOT_FOUND;
1481 else if (errno == EBUSY)
1482 return LIBUSB_ERROR_BUSY;
1483 else if (errno == ENODEV)
1484 return LIBUSB_ERROR_NO_DEVICE;
1486 usbi_err(HANDLE_CTX(handle),
1487 "claim interface failed, error %d errno %d", r, errno);
1488 return LIBUSB_ERROR_OTHER;
1493 static int release_interface(struct libusb_device_handle *handle, int iface)
1495 int fd = _device_handle_priv(handle)->fd;
1496 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1498 if (errno == ENODEV)
1499 return LIBUSB_ERROR_NO_DEVICE;
1501 usbi_err(HANDLE_CTX(handle),
1502 "release interface failed, error %d errno %d", r, errno);
1503 return LIBUSB_ERROR_OTHER;
1508 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1511 int fd = _device_handle_priv(handle)->fd;
1512 struct usbfs_setinterface setintf;
1515 setintf.interface = iface;
1516 setintf.altsetting = altsetting;
1517 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1519 if (errno == EINVAL)
1520 return LIBUSB_ERROR_NOT_FOUND;
1521 else if (errno == ENODEV)
1522 return LIBUSB_ERROR_NO_DEVICE;
1524 usbi_err(HANDLE_CTX(handle),
1525 "setintf failed error %d errno %d", r, errno);
1526 return LIBUSB_ERROR_OTHER;
1532 static int op_clear_halt(struct libusb_device_handle *handle,
1533 unsigned char endpoint)
1535 int fd = _device_handle_priv(handle)->fd;
1536 unsigned int _endpoint = endpoint;
1537 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1539 if (errno == ENOENT)
1540 return LIBUSB_ERROR_NOT_FOUND;
1541 else if (errno == ENODEV)
1542 return LIBUSB_ERROR_NO_DEVICE;
1544 usbi_err(HANDLE_CTX(handle),
1545 "clear_halt failed error %d errno %d", r, errno);
1546 return LIBUSB_ERROR_OTHER;
1552 static int op_reset_device(struct libusb_device_handle *handle)
1554 int fd = _device_handle_priv(handle)->fd;
1557 /* Doing a device reset will cause the usbfs driver to get unbound
1558 from any interfaces it is bound to. By voluntarily unbinding
1559 the usbfs driver ourself, we stop the kernel from rebinding
1560 the interface after reset (which would end up with the interface
1561 getting bound to the in kernel driver if any). */
1562 for (i = 0; i < USB_MAXINTERFACES; i++) {
1563 if (handle->claimed_interfaces & (1L << i)) {
1564 release_interface(handle, i);
1568 usbi_mutex_lock(&handle->lock);
1569 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1571 if (errno == ENODEV) {
1572 ret = LIBUSB_ERROR_NOT_FOUND;
1576 usbi_err(HANDLE_CTX(handle),
1577 "reset failed error %d errno %d", r, errno);
1578 ret = LIBUSB_ERROR_OTHER;
1582 /* And re-claim any interfaces which were claimed before the reset */
1583 for (i = 0; i < USB_MAXINTERFACES; i++) {
1584 if (handle->claimed_interfaces & (1L << i)) {
1586 * A driver may have completed modprobing during
1587 * IOCTL_USBFS_RESET, and bound itself as soon as
1588 * IOCTL_USBFS_RESET released the device lock
1590 r = detach_kernel_driver_and_claim(handle, i);
1592 usbi_warn(HANDLE_CTX(handle),
1593 "failed to re-claim interface %d after reset: %s",
1594 i, libusb_error_name(r));
1595 handle->claimed_interfaces &= ~(1L << i);
1596 ret = LIBUSB_ERROR_NOT_FOUND;
1601 usbi_mutex_unlock(&handle->lock);
1605 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1606 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1608 int r, fd = _device_handle_priv(handle)->fd;
1609 struct usbfs_streams *streams;
1611 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1612 return LIBUSB_ERROR_INVALID_PARAM;
1614 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1616 return LIBUSB_ERROR_NO_MEM;
1618 streams->num_streams = num_streams;
1619 streams->num_eps = num_endpoints;
1620 memcpy(streams->eps, endpoints, num_endpoints);
1622 r = ioctl(fd, req, streams);
1627 if (errno == ENOTTY)
1628 return LIBUSB_ERROR_NOT_SUPPORTED;
1629 else if (errno == EINVAL)
1630 return LIBUSB_ERROR_INVALID_PARAM;
1631 else if (errno == ENODEV)
1632 return LIBUSB_ERROR_NO_DEVICE;
1634 usbi_err(HANDLE_CTX(handle),
1635 "streams-ioctl failed error %d errno %d", r, errno);
1636 return LIBUSB_ERROR_OTHER;
1641 static int op_alloc_streams(struct libusb_device_handle *handle,
1642 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1644 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1645 num_streams, endpoints, num_endpoints);
1648 static int op_free_streams(struct libusb_device_handle *handle,
1649 unsigned char *endpoints, int num_endpoints)
1651 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1652 endpoints, num_endpoints);
1655 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1658 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1659 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1660 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1661 if (buffer == MAP_FAILED) {
1662 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1669 static int op_dev_mem_free(struct libusb_device_handle *handle,
1670 unsigned char *buffer, size_t len)
1672 if (munmap(buffer, len) != 0) {
1673 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1675 return LIBUSB_ERROR_OTHER;
1677 return LIBUSB_SUCCESS;
1681 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1684 int fd = _device_handle_priv(handle)->fd;
1685 struct usbfs_getdriver getdrv;
1688 getdrv.interface = interface;
1689 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1691 if (errno == ENODATA)
1693 else if (errno == ENODEV)
1694 return LIBUSB_ERROR_NO_DEVICE;
1696 usbi_err(HANDLE_CTX(handle),
1697 "get driver failed error %d errno %d", r, errno);
1698 return LIBUSB_ERROR_OTHER;
1701 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1704 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1707 int fd = _device_handle_priv(handle)->fd;
1708 struct usbfs_ioctl command;
1709 struct usbfs_getdriver getdrv;
1712 command.ifno = interface;
1713 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1714 command.data = NULL;
1716 getdrv.interface = interface;
1717 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1718 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1719 return LIBUSB_ERROR_NOT_FOUND;
1721 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1723 if (errno == ENODATA)
1724 return LIBUSB_ERROR_NOT_FOUND;
1725 else if (errno == EINVAL)
1726 return LIBUSB_ERROR_INVALID_PARAM;
1727 else if (errno == ENODEV)
1728 return LIBUSB_ERROR_NO_DEVICE;
1730 usbi_err(HANDLE_CTX(handle),
1731 "detach failed error %d errno %d", r, errno);
1732 return LIBUSB_ERROR_OTHER;
1738 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1741 int fd = _device_handle_priv(handle)->fd;
1742 struct usbfs_ioctl command;
1745 command.ifno = interface;
1746 command.ioctl_code = IOCTL_USBFS_CONNECT;
1747 command.data = NULL;
1749 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1751 if (errno == ENODATA)
1752 return LIBUSB_ERROR_NOT_FOUND;
1753 else if (errno == EINVAL)
1754 return LIBUSB_ERROR_INVALID_PARAM;
1755 else if (errno == ENODEV)
1756 return LIBUSB_ERROR_NO_DEVICE;
1757 else if (errno == EBUSY)
1758 return LIBUSB_ERROR_BUSY;
1760 usbi_err(HANDLE_CTX(handle),
1761 "attach failed error %d errno %d", r, errno);
1762 return LIBUSB_ERROR_OTHER;
1763 } else if (r == 0) {
1764 return LIBUSB_ERROR_NOT_FOUND;
1770 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1773 struct usbfs_disconnect_claim dc;
1774 int r, fd = _device_handle_priv(handle)->fd;
1776 dc.interface = interface;
1777 strcpy(dc.driver, "usbfs");
1778 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1779 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1780 if (r != 0 && errno != ENOTTY) {
1783 return LIBUSB_ERROR_BUSY;
1785 return LIBUSB_ERROR_INVALID_PARAM;
1787 return LIBUSB_ERROR_NO_DEVICE;
1789 usbi_err(HANDLE_CTX(handle),
1790 "disconnect-and-claim failed errno %d", errno);
1791 return LIBUSB_ERROR_OTHER;
1795 /* Fallback code for kernels which don't support the
1796 disconnect-and-claim ioctl */
1797 r = op_detach_kernel_driver(handle, interface);
1798 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1801 return claim_interface(handle, interface);
1804 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1806 if (handle->auto_detach_kernel_driver)
1807 return detach_kernel_driver_and_claim(handle, iface);
1809 return claim_interface(handle, iface);
1812 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1816 r = release_interface(handle, iface);
1820 if (handle->auto_detach_kernel_driver)
1821 op_attach_kernel_driver(handle, iface);
1826 static void op_destroy_device(struct libusb_device *dev)
1828 struct linux_device_priv *priv = _device_priv(dev);
1829 if (priv->descriptors)
1830 free(priv->descriptors);
1831 if (priv->sysfs_dir)
1832 free(priv->sysfs_dir);
1835 /* URBs are discarded in reverse order of submission to avoid races. */
1836 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1838 struct libusb_transfer *transfer =
1839 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1840 struct linux_transfer_priv *tpriv =
1841 usbi_transfer_get_os_priv(itransfer);
1842 struct linux_device_handle_priv *dpriv =
1843 _device_handle_priv(transfer->dev_handle);
1845 struct usbfs_urb *urb;
1847 for (i = last_plus_one - 1; i >= first; i--) {
1848 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1849 urb = tpriv->iso_urbs[i];
1851 urb = &tpriv->urbs[i];
1853 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1856 if (EINVAL == errno) {
1857 usbi_dbg("URB not found --> assuming ready to be reaped");
1858 if (i == (last_plus_one - 1))
1859 ret = LIBUSB_ERROR_NOT_FOUND;
1860 } else if (ENODEV == errno) {
1861 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1862 ret = LIBUSB_ERROR_NO_DEVICE;
1864 usbi_warn(TRANSFER_CTX(transfer),
1865 "unrecognised discard errno %d", errno);
1866 ret = LIBUSB_ERROR_OTHER;
1872 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1875 for (i = 0; i < tpriv->num_urbs; i++) {
1876 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1882 free(tpriv->iso_urbs);
1883 tpriv->iso_urbs = NULL;
1886 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1888 struct libusb_transfer *transfer =
1889 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1890 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1891 struct linux_device_handle_priv *dpriv =
1892 _device_handle_priv(transfer->dev_handle);
1893 struct usbfs_urb *urbs;
1894 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1895 == LIBUSB_ENDPOINT_OUT;
1896 int bulk_buffer_len, use_bulk_continuation;
1900 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1901 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1902 return LIBUSB_ERROR_NOT_SUPPORTED;
1905 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1906 * around this by splitting large transfers into 16k blocks, and then
1907 * submit all urbs at once. it would be simpler to submit one urb at
1908 * a time, but there is a big performance gain doing it this way.
1910 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1911 * using arbritary large transfers can still be a bad idea though, as
1912 * the kernel needs to allocate physical contiguous memory for this,
1913 * which may fail for large buffers.
1915 * The kernel solves this problem by splitting the transfer into
1916 * blocks itself when the host-controller is scatter-gather capable
1917 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1919 * Last, there is the issue of short-transfers when splitting, for
1920 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1921 * is needed, but this is not always available.
1923 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1924 /* Good! Just submit everything in one go */
1925 bulk_buffer_len = transfer->length ? transfer->length : 1;
1926 use_bulk_continuation = 0;
1927 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1928 /* Split the transfers and use bulk-continuation to
1929 avoid issues with short-transfers */
1930 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1931 use_bulk_continuation = 1;
1932 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1933 /* Don't split, assume the kernel can alloc the buffer
1934 (otherwise the submit will fail with -ENOMEM) */
1935 bulk_buffer_len = transfer->length ? transfer->length : 1;
1936 use_bulk_continuation = 0;
1938 /* Bad, splitting without bulk-continuation, short transfers
1939 which end before the last urb will not work reliable! */
1940 /* Note we don't warn here as this is "normal" on kernels <
1941 2.6.32 and not a problem for most applications */
1942 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1943 use_bulk_continuation = 0;
1946 int num_urbs = transfer->length / bulk_buffer_len;
1947 int last_urb_partial = 0;
1949 if (transfer->length == 0) {
1951 } else if ((transfer->length % bulk_buffer_len) > 0) {
1952 last_urb_partial = 1;
1955 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1957 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1959 return LIBUSB_ERROR_NO_MEM;
1961 tpriv->num_urbs = num_urbs;
1962 tpriv->num_retired = 0;
1963 tpriv->reap_action = NORMAL;
1964 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1966 for (i = 0; i < num_urbs; i++) {
1967 struct usbfs_urb *urb = &urbs[i];
1968 urb->usercontext = itransfer;
1969 switch (transfer->type) {
1970 case LIBUSB_TRANSFER_TYPE_BULK:
1971 urb->type = USBFS_URB_TYPE_BULK;
1974 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1975 urb->type = USBFS_URB_TYPE_BULK;
1976 urb->stream_id = itransfer->stream_id;
1978 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1979 urb->type = USBFS_URB_TYPE_INTERRUPT;
1982 urb->endpoint = transfer->endpoint;
1983 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1984 /* don't set the short not ok flag for the last URB */
1985 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1986 urb->flags = USBFS_URB_SHORT_NOT_OK;
1987 if (i == num_urbs - 1 && last_urb_partial)
1988 urb->buffer_length = transfer->length % bulk_buffer_len;
1989 else if (transfer->length == 0)
1990 urb->buffer_length = 0;
1992 urb->buffer_length = bulk_buffer_len;
1994 if (i > 0 && use_bulk_continuation)
1995 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1997 /* we have already checked that the flag is supported */
1998 if (is_out && i == num_urbs - 1 &&
1999 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2000 urb->flags |= USBFS_URB_ZERO_PACKET;
2002 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2004 if (errno == ENODEV) {
2005 r = LIBUSB_ERROR_NO_DEVICE;
2007 usbi_err(TRANSFER_CTX(transfer),
2008 "submiturb failed error %d errno=%d", r, errno);
2009 r = LIBUSB_ERROR_IO;
2012 /* if the first URB submission fails, we can simply free up and
2013 * return failure immediately. */
2015 usbi_dbg("first URB failed, easy peasy");
2021 /* if it's not the first URB that failed, the situation is a bit
2022 * tricky. we may need to discard all previous URBs. there are
2024 * - discarding is asynchronous - discarded urbs will be reaped
2025 * later. the user must not have freed the transfer when the
2026 * discarded URBs are reaped, otherwise libusb will be using
2028 * - the earlier URBs may have completed successfully and we do
2029 * not want to throw away any data.
2030 * - this URB failing may be no error; EREMOTEIO means that
2031 * this transfer simply didn't need all the URBs we submitted
2032 * so, we report that the transfer was submitted successfully and
2033 * in case of error we discard all previous URBs. later when
2034 * the final reap completes we can report error to the user,
2035 * or success if an earlier URB was completed successfully.
2037 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2039 /* The URBs we haven't submitted yet we count as already
2041 tpriv->num_retired += num_urbs - i;
2043 /* If we completed short then don't try to discard. */
2044 if (COMPLETED_EARLY == tpriv->reap_action)
2047 discard_urbs(itransfer, 0, i);
2049 usbi_dbg("reporting successful submission but waiting for %d "
2050 "discards before reporting error", i);
2058 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2060 struct libusb_transfer *transfer =
2061 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2062 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2063 struct linux_device_handle_priv *dpriv =
2064 _device_handle_priv(transfer->dev_handle);
2065 struct usbfs_urb **urbs;
2066 int num_packets = transfer->num_iso_packets;
2067 int num_packets_remaining;
2070 unsigned int packet_len;
2071 unsigned int total_len = 0;
2072 unsigned char *urb_buffer = transfer->buffer;
2074 if (num_packets < 1)
2075 return LIBUSB_ERROR_INVALID_PARAM;
2077 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2078 * at least three times, but we attempt to detect this limit during
2079 * init and check it here. if the kernel rejects the request due to
2080 * its size, we return an error indicating such to the user.
2082 for (i = 0; i < num_packets; i++) {
2083 packet_len = transfer->iso_packet_desc[i].length;
2085 if (packet_len > max_iso_packet_len) {
2086 usbi_warn(TRANSFER_CTX(transfer),
2087 "iso packet length of %u bytes exceeds maximum of %u bytes",
2088 packet_len, max_iso_packet_len);
2089 return LIBUSB_ERROR_INVALID_PARAM;
2092 total_len += packet_len;
2095 if (transfer->length < (int)total_len)
2096 return LIBUSB_ERROR_INVALID_PARAM;
2098 /* usbfs limits the number of iso packets per URB */
2099 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2101 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2104 urbs = calloc(num_urbs, sizeof(*urbs));
2106 return LIBUSB_ERROR_NO_MEM;
2108 tpriv->iso_urbs = urbs;
2109 tpriv->num_urbs = num_urbs;
2110 tpriv->num_retired = 0;
2111 tpriv->reap_action = NORMAL;
2112 tpriv->iso_packet_offset = 0;
2114 /* allocate + initialize each URB with the correct number of packets */
2115 num_packets_remaining = num_packets;
2116 for (i = 0, j = 0; i < num_urbs; i++) {
2117 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2118 struct usbfs_urb *urb;
2122 alloc_size = sizeof(*urb)
2123 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2124 urb = calloc(1, alloc_size);
2126 free_iso_urbs(tpriv);
2127 return LIBUSB_ERROR_NO_MEM;
2131 /* populate packet lengths */
2132 for (k = 0; k < num_packets_in_urb; j++, k++) {
2133 packet_len = transfer->iso_packet_desc[j].length;
2134 urb->buffer_length += packet_len;
2135 urb->iso_frame_desc[k].length = packet_len;
2138 urb->usercontext = itransfer;
2139 urb->type = USBFS_URB_TYPE_ISO;
2140 /* FIXME: interface for non-ASAP data? */
2141 urb->flags = USBFS_URB_ISO_ASAP;
2142 urb->endpoint = transfer->endpoint;
2143 urb->number_of_packets = num_packets_in_urb;
2144 urb->buffer = urb_buffer;
2146 urb_buffer += urb->buffer_length;
2147 num_packets_remaining -= num_packets_in_urb;
2151 for (i = 0; i < num_urbs; i++) {
2152 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2154 if (errno == ENODEV) {
2155 r = LIBUSB_ERROR_NO_DEVICE;
2156 } else if (errno == EINVAL) {
2157 usbi_warn(TRANSFER_CTX(transfer),
2158 "submiturb failed, transfer too large");
2159 r = LIBUSB_ERROR_INVALID_PARAM;
2160 } else if (errno == EMSGSIZE) {
2161 usbi_warn(TRANSFER_CTX(transfer),
2162 "submiturb failed, iso packet length too large");
2163 r = LIBUSB_ERROR_INVALID_PARAM;
2165 usbi_err(TRANSFER_CTX(transfer),
2166 "submiturb failed error %d errno=%d", r, errno);
2167 r = LIBUSB_ERROR_IO;
2170 /* if the first URB submission fails, we can simply free up and
2171 * return failure immediately. */
2173 usbi_dbg("first URB failed, easy peasy");
2174 free_iso_urbs(tpriv);
2178 /* if it's not the first URB that failed, the situation is a bit
2179 * tricky. we must discard all previous URBs. there are
2181 * - discarding is asynchronous - discarded urbs will be reaped
2182 * later. the user must not have freed the transfer when the
2183 * discarded URBs are reaped, otherwise libusb will be using
2185 * - the earlier URBs may have completed successfully and we do
2186 * not want to throw away any data.
2187 * so, in this case we discard all the previous URBs BUT we report
2188 * that the transfer was submitted successfully. then later when
2189 * the final discard completes we can report error to the user.
2191 tpriv->reap_action = SUBMIT_FAILED;
2193 /* The URBs we haven't submitted yet we count as already
2195 tpriv->num_retired = num_urbs - i;
2196 discard_urbs(itransfer, 0, i);
2198 usbi_dbg("reporting successful submission but waiting for %d "
2199 "discards before reporting error", i);
2207 static int submit_control_transfer(struct usbi_transfer *itransfer)
2209 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2210 struct libusb_transfer *transfer =
2211 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2212 struct linux_device_handle_priv *dpriv =
2213 _device_handle_priv(transfer->dev_handle);
2214 struct usbfs_urb *urb;
2217 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2218 return LIBUSB_ERROR_INVALID_PARAM;
2220 urb = calloc(1, sizeof(struct usbfs_urb));
2222 return LIBUSB_ERROR_NO_MEM;
2224 tpriv->num_urbs = 1;
2225 tpriv->reap_action = NORMAL;
2227 urb->usercontext = itransfer;
2228 urb->type = USBFS_URB_TYPE_CONTROL;
2229 urb->endpoint = transfer->endpoint;
2230 urb->buffer = transfer->buffer;
2231 urb->buffer_length = transfer->length;
2233 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2237 if (errno == ENODEV)
2238 return LIBUSB_ERROR_NO_DEVICE;
2240 usbi_err(TRANSFER_CTX(transfer),
2241 "submiturb failed error %d errno=%d", r, errno);
2242 return LIBUSB_ERROR_IO;
2247 static int op_submit_transfer(struct usbi_transfer *itransfer)
2249 struct libusb_transfer *transfer =
2250 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2252 switch (transfer->type) {
2253 case LIBUSB_TRANSFER_TYPE_CONTROL:
2254 return submit_control_transfer(itransfer);
2255 case LIBUSB_TRANSFER_TYPE_BULK:
2256 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2257 return submit_bulk_transfer(itransfer);
2258 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2259 return submit_bulk_transfer(itransfer);
2260 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2261 return submit_iso_transfer(itransfer);
2263 usbi_err(TRANSFER_CTX(transfer),
2264 "unknown endpoint type %d", transfer->type);
2265 return LIBUSB_ERROR_INVALID_PARAM;
2269 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2271 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2272 struct libusb_transfer *transfer =
2273 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2277 return LIBUSB_ERROR_NOT_FOUND;
2279 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2283 switch (transfer->type) {
2284 case LIBUSB_TRANSFER_TYPE_BULK:
2285 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2286 if (tpriv->reap_action == ERROR)
2288 /* else, fall through */
2290 tpriv->reap_action = CANCELLED;
2296 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2298 struct libusb_transfer *transfer =
2299 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2300 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2302 switch (transfer->type) {
2303 case LIBUSB_TRANSFER_TYPE_CONTROL:
2304 case LIBUSB_TRANSFER_TYPE_BULK:
2305 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2306 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2312 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2313 if (tpriv->iso_urbs) {
2314 free_iso_urbs(tpriv);
2315 tpriv->iso_urbs = NULL;
2319 usbi_err(TRANSFER_CTX(transfer),
2320 "unknown endpoint type %d", transfer->type);
2324 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2325 struct usbfs_urb *urb)
2327 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2328 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2329 int urb_idx = urb - tpriv->urbs;
2331 usbi_mutex_lock(&itransfer->lock);
2332 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2333 urb_idx + 1, tpriv->num_urbs);
2335 tpriv->num_retired++;
2337 if (tpriv->reap_action != NORMAL) {
2338 /* cancelled, submit_fail, or completed early */
2339 usbi_dbg("abnormal reap: urb status %d", urb->status);
2341 /* even though we're in the process of cancelling, it's possible that
2342 * we may receive some data in these URBs that we don't want to lose.
2344 * 1. while the kernel is cancelling all the packets that make up an
2345 * URB, a few of them might complete. so we get back a successful
2346 * cancellation *and* some data.
2347 * 2. we receive a short URB which marks the early completion condition,
2348 * so we start cancelling the remaining URBs. however, we're too
2349 * slow and another URB completes (or at least completes partially).
2350 * (this can't happen since we always use BULK_CONTINUATION.)
2352 * When this happens, our objectives are not to lose any "surplus" data,
2353 * and also to stick it at the end of the previously-received data
2354 * (closing any holes), so that libusb reports the total amount of
2355 * transferred data and presents it in a contiguous chunk.
2357 if (urb->actual_length > 0) {
2358 unsigned char *target = transfer->buffer + itransfer->transferred;
2359 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2360 if (urb->buffer != target) {
2361 usbi_dbg("moving surplus data from offset %d to offset %d",
2362 (unsigned char *) urb->buffer - transfer->buffer,
2363 target - transfer->buffer);
2364 memmove(target, urb->buffer, urb->actual_length);
2366 itransfer->transferred += urb->actual_length;
2369 if (tpriv->num_retired == tpriv->num_urbs) {
2370 usbi_dbg("abnormal reap: last URB handled, reporting");
2371 if (tpriv->reap_action != COMPLETED_EARLY &&
2372 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2373 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2379 itransfer->transferred += urb->actual_length;
2381 /* Many of these errors can occur on *any* urb of a multi-urb
2382 * transfer. When they do, we tear down the rest of the transfer.
2384 switch (urb->status) {
2387 case -EREMOTEIO: /* short transfer */
2389 case -ENOENT: /* cancelled */
2394 usbi_dbg("device removed");
2395 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2396 goto cancel_remaining;
2398 usbi_dbg("detected endpoint stall");
2399 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2400 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2401 goto cancel_remaining;
2403 /* overflow can only ever occur in the last urb */
2404 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2405 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2406 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2413 usbi_dbg("low level error %d", urb->status);
2414 tpriv->reap_action = ERROR;
2415 goto cancel_remaining;
2417 usbi_warn(ITRANSFER_CTX(itransfer),
2418 "unrecognised urb status %d", urb->status);
2419 tpriv->reap_action = ERROR;
2420 goto cancel_remaining;
2423 /* if we're the last urb or we got less data than requested then we're
2425 if (urb_idx == tpriv->num_urbs - 1) {
2426 usbi_dbg("last URB in transfer --> complete!");
2428 } else if (urb->actual_length < urb->buffer_length) {
2429 usbi_dbg("short transfer %d/%d --> complete!",
2430 urb->actual_length, urb->buffer_length);
2431 if (tpriv->reap_action == NORMAL)
2432 tpriv->reap_action = COMPLETED_EARLY;
2437 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2438 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2440 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2443 /* cancel remaining urbs and wait for their completion before
2444 * reporting results */
2445 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2448 usbi_mutex_unlock(&itransfer->lock);
2454 usbi_mutex_unlock(&itransfer->lock);
2455 return CANCELLED == tpriv->reap_action ?
2456 usbi_handle_transfer_cancellation(itransfer) :
2457 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2460 static int handle_iso_completion(struct usbi_transfer *itransfer,
2461 struct usbfs_urb *urb)
2463 struct libusb_transfer *transfer =
2464 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2465 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2466 int num_urbs = tpriv->num_urbs;
2469 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2471 usbi_mutex_lock(&itransfer->lock);
2472 for (i = 0; i < num_urbs; i++) {
2473 if (urb == tpriv->iso_urbs[i]) {
2479 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2480 usbi_mutex_unlock(&itransfer->lock);
2481 return LIBUSB_ERROR_NOT_FOUND;
2484 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2487 /* copy isochronous results back in */
2489 for (i = 0; i < urb->number_of_packets; i++) {
2490 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2491 struct libusb_iso_packet_descriptor *lib_desc =
2492 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2493 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2494 switch (urb_desc->status) {
2497 case -ENOENT: /* cancelled */
2502 usbi_dbg("device removed");
2503 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2506 usbi_dbg("detected endpoint stall");
2507 lib_desc->status = LIBUSB_TRANSFER_STALL;
2510 usbi_dbg("overflow error");
2511 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2519 usbi_dbg("low-level USB error %d", urb_desc->status);
2520 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2523 usbi_warn(TRANSFER_CTX(transfer),
2524 "unrecognised urb status %d", urb_desc->status);
2525 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2528 lib_desc->actual_length = urb_desc->actual_length;
2531 tpriv->num_retired++;
2533 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2534 usbi_dbg("CANCEL: urb status %d", urb->status);
2536 if (tpriv->num_retired == num_urbs) {
2537 usbi_dbg("CANCEL: last URB handled, reporting");
2538 free_iso_urbs(tpriv);
2539 if (tpriv->reap_action == CANCELLED) {
2540 usbi_mutex_unlock(&itransfer->lock);
2541 return usbi_handle_transfer_cancellation(itransfer);
2543 usbi_mutex_unlock(&itransfer->lock);
2544 return usbi_handle_transfer_completion(itransfer,
2545 LIBUSB_TRANSFER_ERROR);
2551 switch (urb->status) {
2554 case -ENOENT: /* cancelled */
2558 usbi_dbg("device removed");
2559 status = LIBUSB_TRANSFER_NO_DEVICE;
2562 usbi_warn(TRANSFER_CTX(transfer),
2563 "unrecognised urb status %d", urb->status);
2564 status = LIBUSB_TRANSFER_ERROR;
2568 /* if we're the last urb then we're done */
2569 if (urb_idx == num_urbs) {
2570 usbi_dbg("last URB in transfer --> complete!");
2571 free_iso_urbs(tpriv);
2572 usbi_mutex_unlock(&itransfer->lock);
2573 return usbi_handle_transfer_completion(itransfer, status);
2577 usbi_mutex_unlock(&itransfer->lock);
2581 static int handle_control_completion(struct usbi_transfer *itransfer,
2582 struct usbfs_urb *urb)
2584 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2587 usbi_mutex_lock(&itransfer->lock);
2588 usbi_dbg("handling completion status %d", urb->status);
2590 itransfer->transferred += urb->actual_length;
2592 if (tpriv->reap_action == CANCELLED) {
2593 if (urb->status != 0 && urb->status != -ENOENT)
2594 usbi_warn(ITRANSFER_CTX(itransfer),
2595 "cancel: unrecognised urb status %d", urb->status);
2598 usbi_mutex_unlock(&itransfer->lock);
2599 return usbi_handle_transfer_cancellation(itransfer);
2602 switch (urb->status) {
2604 status = LIBUSB_TRANSFER_COMPLETED;
2606 case -ENOENT: /* cancelled */
2607 status = LIBUSB_TRANSFER_CANCELLED;
2611 usbi_dbg("device removed");
2612 status = LIBUSB_TRANSFER_NO_DEVICE;
2615 usbi_dbg("unsupported control request");
2616 status = LIBUSB_TRANSFER_STALL;
2619 usbi_dbg("control overflow error");
2620 status = LIBUSB_TRANSFER_OVERFLOW;
2627 usbi_dbg("low-level bus error occurred");
2628 status = LIBUSB_TRANSFER_ERROR;
2631 usbi_warn(ITRANSFER_CTX(itransfer),
2632 "unrecognised urb status %d", urb->status);
2633 status = LIBUSB_TRANSFER_ERROR;
2639 usbi_mutex_unlock(&itransfer->lock);
2640 return usbi_handle_transfer_completion(itransfer, status);
2643 static int reap_for_handle(struct libusb_device_handle *handle)
2645 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2647 struct usbfs_urb *urb;
2648 struct usbi_transfer *itransfer;
2649 struct libusb_transfer *transfer;
2651 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2652 if (r == -1 && errno == EAGAIN)
2655 if (errno == ENODEV)
2656 return LIBUSB_ERROR_NO_DEVICE;
2658 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2660 return LIBUSB_ERROR_IO;
2663 itransfer = urb->usercontext;
2664 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2666 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2667 urb->actual_length);
2669 switch (transfer->type) {
2670 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2671 return handle_iso_completion(itransfer, urb);
2672 case LIBUSB_TRANSFER_TYPE_BULK:
2673 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2674 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2675 return handle_bulk_completion(itransfer, urb);
2676 case LIBUSB_TRANSFER_TYPE_CONTROL:
2677 return handle_control_completion(itransfer, urb);
2679 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2681 return LIBUSB_ERROR_OTHER;
2685 static int op_handle_events(struct libusb_context *ctx,
2686 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2691 usbi_mutex_lock(&ctx->open_devs_lock);
2692 for (i = 0; i < nfds && num_ready > 0; i++) {
2693 struct pollfd *pollfd = &fds[i];
2694 struct libusb_device_handle *handle;
2695 struct linux_device_handle_priv *hpriv = NULL;
2697 if (!pollfd->revents)
2701 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2702 hpriv = _device_handle_priv(handle);
2703 if (hpriv->fd == pollfd->fd)
2707 if (!hpriv || hpriv->fd != pollfd->fd) {
2708 usbi_err(ctx, "cannot find handle for fd %d",
2713 if (pollfd->revents & POLLERR) {
2714 /* remove the fd from the pollfd set so that it doesn't continuously
2715 * trigger an event, and flag that it has been removed so op_close()
2716 * doesn't try to remove it a second time */
2717 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2718 hpriv->fd_removed = 1;
2720 /* device will still be marked as attached if hotplug monitor thread
2721 * hasn't processed remove event yet */
2722 usbi_mutex_static_lock(&linux_hotplug_lock);
2723 if (handle->dev->attached)
2724 linux_device_disconnected(handle->dev->bus_number,
2725 handle->dev->device_address);
2726 usbi_mutex_static_unlock(&linux_hotplug_lock);
2728 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2730 r = reap_for_handle(handle);
2734 usbi_handle_disconnect(handle);
2739 r = reap_for_handle(handle);
2741 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2749 usbi_mutex_unlock(&ctx->open_devs_lock);
2753 static int op_clock_gettime(int clk_id, struct timespec *tp)
2756 case USBI_CLOCK_MONOTONIC:
2757 return clock_gettime(monotonic_clkid, tp);
2758 case USBI_CLOCK_REALTIME:
2759 return clock_gettime(CLOCK_REALTIME, tp);
2761 return LIBUSB_ERROR_INVALID_PARAM;
2765 #ifdef USBI_TIMERFD_AVAILABLE
2766 static clockid_t op_get_timerfd_clockid(void)
2768 return monotonic_clkid;
2773 const struct usbi_os_backend usbi_backend = {
2774 .name = "Linux usbfs",
2775 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2778 .get_device_list = NULL,
2779 .hotplug_poll = op_hotplug_poll,
2780 .get_device_descriptor = op_get_device_descriptor,
2781 .get_active_config_descriptor = op_get_active_config_descriptor,
2782 .get_config_descriptor = op_get_config_descriptor,
2783 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2787 .get_configuration = op_get_configuration,
2788 .set_configuration = op_set_configuration,
2789 .claim_interface = op_claim_interface,
2790 .release_interface = op_release_interface,
2792 .set_interface_altsetting = op_set_interface,
2793 .clear_halt = op_clear_halt,
2794 .reset_device = op_reset_device,
2796 .alloc_streams = op_alloc_streams,
2797 .free_streams = op_free_streams,
2799 .dev_mem_alloc = op_dev_mem_alloc,
2800 .dev_mem_free = op_dev_mem_free,
2802 .kernel_driver_active = op_kernel_driver_active,
2803 .detach_kernel_driver = op_detach_kernel_driver,
2804 .attach_kernel_driver = op_attach_kernel_driver,
2806 .destroy_device = op_destroy_device,
2808 .submit_transfer = op_submit_transfer,
2809 .cancel_transfer = op_cancel_transfer,
2810 .clear_transfer_priv = op_clear_transfer_priv,
2812 .handle_events = op_handle_events,
2814 .clock_gettime = op_clock_gettime,
2816 #ifdef USBI_TIMERFD_AVAILABLE
2817 .get_timerfd_clockid = op_get_timerfd_clockid,
2820 .device_priv_size = sizeof(struct linux_device_priv),
2821 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2822 .transfer_priv_size = sizeof(struct linux_transfer_priv),