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)
694 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
695 /* can't use sysfs to read the bus and device number if the
696 * device has been detached */
697 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
698 if (NULL == dev_node) {
699 return LIBUSB_ERROR_OTHER;
702 /* will this work with all supported kernel versions? */
703 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
704 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
705 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
706 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
709 return LIBUSB_SUCCESS;
712 usbi_dbg("scan %s", sys_name);
714 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
717 if (sysfs_attr > 255)
718 return LIBUSB_ERROR_INVALID_PARAM;
719 *busnum = (uint8_t) sysfs_attr;
721 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
724 if (sysfs_attr > 255)
725 return LIBUSB_ERROR_INVALID_PARAM;
727 *devaddr = (uint8_t) sysfs_attr;
729 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
731 return LIBUSB_SUCCESS;
734 /* Return offset of the next descriptor with the given type */
735 static int seek_to_next_descriptor(struct libusb_context *ctx,
736 uint8_t descriptor_type, unsigned char *buffer, int size)
738 struct usb_descriptor_header header;
741 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
743 return LIBUSB_ERROR_NOT_FOUND;
746 usbi_err(ctx, "short descriptor read %d/2", size);
747 return LIBUSB_ERROR_IO;
749 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
751 if (i && header.bDescriptorType == descriptor_type)
754 usbi_err(ctx, "bLength overflow by %d bytes", -size);
755 return LIBUSB_ERROR_IO;
758 /* Return offset to next config */
759 static int seek_to_next_config(struct libusb_device *dev,
760 unsigned char *buffer, int size)
762 struct libusb_context *ctx = DEVICE_CTX(dev);
763 struct linux_device_priv *priv = _device_priv(dev);
764 struct libusb_config_descriptor config;
767 return LIBUSB_ERROR_NOT_FOUND;
769 if (size < LIBUSB_DT_CONFIG_SIZE) {
770 usbi_err(ctx, "short descriptor read %d/%d",
771 size, LIBUSB_DT_CONFIG_SIZE);
772 return LIBUSB_ERROR_IO;
775 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
776 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
777 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
778 config.bDescriptorType);
779 return LIBUSB_ERROR_IO;
783 * In usbfs the config descriptors are config.wTotalLength bytes apart,
784 * with any short reads from the device appearing as holes in the file.
786 * In sysfs wTotalLength is ignored, instead the kernel returns a
787 * config descriptor with verified bLength fields, with descriptors
788 * with an invalid bLength removed.
790 if (priv->sysfs_dir && sysfs_has_descriptors) {
791 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
793 if (next == LIBUSB_ERROR_NOT_FOUND)
798 if (next != config.wTotalLength)
799 usbi_warn(ctx, "config length mismatch wTotalLength "
800 "%d real %d", config.wTotalLength, next);
803 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
804 usbi_err(ctx, "invalid wTotalLength %d",
805 config.wTotalLength);
806 return LIBUSB_ERROR_IO;
807 } else if (config.wTotalLength > size) {
808 usbi_warn(ctx, "short descriptor read %d/%d",
809 size, config.wTotalLength);
812 return config.wTotalLength;
816 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
817 uint8_t value, unsigned char **buffer, int *host_endian)
819 struct linux_device_priv *priv = _device_priv(dev);
820 unsigned char *descriptors = priv->descriptors;
821 int size = priv->descriptors_len;
822 struct libusb_config_descriptor *config;
825 /* Unlike the device desc. config descs. are always in raw format */
828 /* Skip device header */
829 descriptors += DEVICE_DESC_LENGTH;
830 size -= DEVICE_DESC_LENGTH;
832 /* Seek till the config is found, or till "EOF" */
834 int next = seek_to_next_config(dev, descriptors, size);
837 config = (struct libusb_config_descriptor *)descriptors;
838 if (config->bConfigurationValue == value) {
839 *buffer = descriptors;
847 static int op_get_active_config_descriptor(struct libusb_device *dev,
848 unsigned char *buffer, size_t len, int *host_endian)
850 struct linux_device_priv *priv = _device_priv(dev);
852 unsigned char *config_desc;
854 if (priv->sysfs_dir && sysfs_can_relate_devices) {
855 r = sysfs_get_active_config(dev, &config);
859 /* Use cached bConfigurationValue */
860 config = priv->active_config;
863 return LIBUSB_ERROR_NOT_FOUND;
865 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
870 len = MIN(len, (size_t)r);
871 memcpy(buffer, config_desc, len);
875 static int op_get_config_descriptor(struct libusb_device *dev,
876 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
878 struct linux_device_priv *priv = _device_priv(dev);
879 unsigned char *descriptors = priv->descriptors;
880 int i, r, size = priv->descriptors_len;
882 /* Unlike the device desc. config descs. are always in raw format */
885 /* Skip device header */
886 descriptors += DEVICE_DESC_LENGTH;
887 size -= DEVICE_DESC_LENGTH;
889 /* Seek till the config is found, or till "EOF" */
891 r = seek_to_next_config(dev, descriptors, size);
894 if (i == config_index)
900 len = MIN(len, (size_t)r);
901 memcpy(buffer, descriptors, len);
905 /* send a control message to retrieve active configuration */
906 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
908 struct linux_device_priv *priv = _device_priv(dev);
909 unsigned char active_config = 0;
912 struct usbfs_ctrltransfer ctrl = {
913 .bmRequestType = LIBUSB_ENDPOINT_IN,
914 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
919 .data = &active_config
922 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
925 return LIBUSB_ERROR_NO_DEVICE;
927 /* we hit this error path frequently with buggy devices :( */
928 usbi_warn(DEVICE_CTX(dev),
929 "get_configuration failed ret=%d errno=%d", r, errno);
930 priv->active_config = -1;
932 if (active_config > 0) {
933 priv->active_config = active_config;
935 /* some buggy devices have a configuration 0, but we're
936 * reaching into the corner of a corner case here, so let's
937 * not support buggy devices in these circumstances.
938 * stick to the specs: a configuration value of 0 means
940 usbi_warn(DEVICE_CTX(dev),
941 "active cfg 0? assuming unconfigured device");
942 priv->active_config = -1;
946 return LIBUSB_SUCCESS;
949 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
950 uint8_t devaddr, const char *sysfs_dir)
952 struct linux_device_priv *priv = _device_priv(dev);
953 struct libusb_context *ctx = DEVICE_CTX(dev);
954 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
958 dev->bus_number = busnum;
959 dev->device_address = devaddr;
962 priv->sysfs_dir = strdup(sysfs_dir);
963 if (!priv->sysfs_dir)
964 return LIBUSB_ERROR_NO_MEM;
966 /* Note speed can contain 1.5, in this case __read_sysfs_attr
967 will stop parsing at the '.' and return 1 */
968 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
971 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
972 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
973 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
974 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
975 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
977 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
982 /* cache descriptors in memory */
983 if (sysfs_dir && sysfs_has_descriptors)
984 fd = _open_sysfs_attr(dev, "descriptors");
986 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
991 descriptors_size *= 2;
992 priv->descriptors = usbi_reallocf(priv->descriptors,
994 if (!priv->descriptors) {
996 return LIBUSB_ERROR_NO_MEM;
998 /* usbfs has holes in the file */
999 if (!(sysfs_dir && sysfs_has_descriptors)) {
1000 memset(priv->descriptors + priv->descriptors_len,
1001 0, descriptors_size - priv->descriptors_len);
1003 r = read(fd, priv->descriptors + priv->descriptors_len,
1004 descriptors_size - priv->descriptors_len);
1006 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1009 return LIBUSB_ERROR_IO;
1011 priv->descriptors_len += r;
1012 } while (priv->descriptors_len == descriptors_size);
1016 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1017 usbi_err(ctx, "short descriptor read (%d)",
1018 priv->descriptors_len);
1019 return LIBUSB_ERROR_IO;
1022 if (sysfs_dir && sysfs_can_relate_devices)
1023 return LIBUSB_SUCCESS;
1025 /* cache active config */
1026 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1028 /* cannot send a control message to determine the active
1029 * config. just assume the first one is active. */
1030 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1031 "active configuration descriptor");
1032 if (priv->descriptors_len >=
1033 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1034 struct libusb_config_descriptor config;
1035 usbi_parse_descriptor(
1036 priv->descriptors + DEVICE_DESC_LENGTH,
1037 "bbwbbbbb", &config, 0);
1038 priv->active_config = config.bConfigurationValue;
1040 priv->active_config = -1; /* No config dt */
1042 return LIBUSB_SUCCESS;
1045 r = usbfs_get_active_config(dev, fd);
1051 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1053 struct libusb_context *ctx = DEVICE_CTX(dev);
1054 struct libusb_device *it;
1055 char *parent_sysfs_dir, *tmp;
1056 int ret, add_parent = 1;
1058 /* XXX -- can we figure out the topology when using usbfs? */
1059 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1060 /* either using usbfs or finding the parent of a root hub */
1061 return LIBUSB_SUCCESS;
1064 parent_sysfs_dir = strdup(sysfs_dir);
1065 if (NULL == parent_sysfs_dir) {
1066 return LIBUSB_ERROR_NO_MEM;
1068 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1069 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1070 dev->port_number = atoi(tmp + 1);
1073 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1075 free (parent_sysfs_dir);
1076 return LIBUSB_SUCCESS;
1079 /* is the parent a root hub? */
1080 if (NULL == strchr(parent_sysfs_dir, '-')) {
1081 tmp = parent_sysfs_dir;
1082 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1085 return LIBUSB_ERROR_NO_MEM;
1090 /* find the parent in the context */
1091 usbi_mutex_lock(&ctx->usb_devs_lock);
1092 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1093 struct linux_device_priv *priv = _device_priv(it);
1094 if (priv->sysfs_dir) {
1095 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1096 dev->parent_dev = libusb_ref_device(it);
1101 usbi_mutex_unlock(&ctx->usb_devs_lock);
1103 if (!dev->parent_dev && add_parent) {
1104 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1106 sysfs_scan_device(ctx, parent_sysfs_dir);
1111 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1112 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1114 free (parent_sysfs_dir);
1116 return LIBUSB_SUCCESS;
1119 int linux_enumerate_device(struct libusb_context *ctx,
1120 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1122 unsigned long session_id;
1123 struct libusb_device *dev;
1126 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1127 * will be reused. instead we should add a simple sysfs attribute with
1129 session_id = busnum << 8 | devaddr;
1130 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1133 dev = usbi_get_device_by_session_id(ctx, session_id);
1135 /* device already exists in the context */
1136 usbi_dbg("session_id %ld already exists", session_id);
1137 libusb_unref_device(dev);
1138 return LIBUSB_SUCCESS;
1141 usbi_dbg("allocating new device for %d/%d (session %ld)",
1142 busnum, devaddr, session_id);
1143 dev = usbi_alloc_device(ctx, session_id);
1145 return LIBUSB_ERROR_NO_MEM;
1147 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1150 r = usbi_sanitize_device(dev);
1154 r = linux_get_parent_info(dev, sysfs_dir);
1159 libusb_unref_device(dev);
1161 usbi_connect_device(dev);
1166 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1168 struct libusb_context *ctx;
1170 usbi_mutex_static_lock(&active_contexts_lock);
1171 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1172 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1174 usbi_mutex_static_unlock(&active_contexts_lock);
1177 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1179 struct libusb_context *ctx;
1180 struct libusb_device *dev;
1181 unsigned long session_id = busnum << 8 | devaddr;
1183 usbi_mutex_static_lock(&active_contexts_lock);
1184 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1185 dev = usbi_get_device_by_session_id (ctx, session_id);
1187 usbi_disconnect_device (dev);
1188 libusb_unref_device(dev);
1190 usbi_dbg("device not found for session %x", session_id);
1193 usbi_mutex_static_unlock(&active_contexts_lock);
1196 #if !defined(USE_UDEV)
1197 /* open a bus directory and adds all discovered devices to the context */
1198 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1201 char dirpath[PATH_MAX];
1202 struct dirent *entry;
1203 int r = LIBUSB_ERROR_IO;
1205 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1206 usbi_dbg("%s", dirpath);
1207 dir = opendir(dirpath);
1209 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1210 /* FIXME: should handle valid race conditions like hub unplugged
1211 * during directory iteration - this is not an error */
1215 while ((entry = readdir(dir))) {
1218 if (entry->d_name[0] == '.')
1221 devaddr = atoi(entry->d_name);
1223 usbi_dbg("unknown dir entry %s", entry->d_name);
1227 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1228 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1239 static int usbfs_get_device_list(struct libusb_context *ctx)
1241 struct dirent *entry;
1242 DIR *buses = opendir(usbfs_path);
1246 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1247 return LIBUSB_ERROR_IO;
1250 while ((entry = readdir(buses))) {
1253 if (entry->d_name[0] == '.')
1258 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1261 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1263 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1267 busnum = atoi(entry->d_name);
1269 usbi_dbg("unknown dir entry %s", entry->d_name);
1273 r = usbfs_scan_busdir(ctx, busnum);
1285 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1287 uint8_t busnum, devaddr;
1290 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1291 if (LIBUSB_SUCCESS != ret) {
1295 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1299 #if !defined(USE_UDEV)
1300 static int sysfs_get_device_list(struct libusb_context *ctx)
1302 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1303 struct dirent *entry;
1304 int num_devices = 0;
1305 int num_enumerated = 0;
1308 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1309 return LIBUSB_ERROR_IO;
1312 while ((entry = readdir(devices))) {
1313 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1314 || strchr(entry->d_name, ':'))
1319 if (sysfs_scan_device(ctx, entry->d_name)) {
1320 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1329 /* successful if at least one device was enumerated or no devices were found */
1330 if (num_enumerated || !num_devices)
1331 return LIBUSB_SUCCESS;
1333 return LIBUSB_ERROR_IO;
1336 static int linux_default_scan_devices (struct libusb_context *ctx)
1338 /* we can retrieve device list and descriptors from sysfs or usbfs.
1339 * sysfs is preferable, because if we use usbfs we end up resuming
1340 * any autosuspended USB devices. however, sysfs is not available
1341 * everywhere, so we need a usbfs fallback too.
1343 * as described in the "sysfs vs usbfs" comment at the top of this
1344 * file, sometimes we have sysfs but not enough information to
1345 * relate sysfs devices to usbfs nodes. op_init() determines the
1346 * adequacy of sysfs and sets sysfs_can_relate_devices.
1348 if (sysfs_can_relate_devices != 0)
1349 return sysfs_get_device_list(ctx);
1351 return usbfs_get_device_list(ctx);
1355 static int op_open(struct libusb_device_handle *handle)
1357 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1360 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1361 if (hpriv->fd < 0) {
1362 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1363 /* device will still be marked as attached if hotplug monitor thread
1364 * hasn't processed remove event yet */
1365 usbi_mutex_static_lock(&linux_hotplug_lock);
1366 if (handle->dev->attached) {
1367 usbi_dbg("open failed with no device, but device still attached");
1368 linux_device_disconnected(handle->dev->bus_number,
1369 handle->dev->device_address);
1371 usbi_mutex_static_unlock(&linux_hotplug_lock);
1376 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1378 if (errno == ENOTTY)
1379 usbi_dbg("getcap not available");
1381 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1383 if (supports_flag_zero_packet)
1384 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1385 if (supports_flag_bulk_continuation)
1386 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1389 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1396 static void op_close(struct libusb_device_handle *dev_handle)
1398 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1399 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1400 if (!hpriv->fd_removed)
1401 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1405 static int op_get_configuration(struct libusb_device_handle *handle,
1408 struct linux_device_priv *priv = _device_priv(handle->dev);
1411 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1412 r = sysfs_get_active_config(handle->dev, config);
1414 r = usbfs_get_active_config(handle->dev,
1415 _device_handle_priv(handle)->fd);
1416 if (r == LIBUSB_SUCCESS)
1417 *config = priv->active_config;
1422 if (*config == -1) {
1423 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1430 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1432 struct linux_device_priv *priv = _device_priv(handle->dev);
1433 int fd = _device_handle_priv(handle)->fd;
1434 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1436 if (errno == EINVAL)
1437 return LIBUSB_ERROR_NOT_FOUND;
1438 else if (errno == EBUSY)
1439 return LIBUSB_ERROR_BUSY;
1440 else if (errno == ENODEV)
1441 return LIBUSB_ERROR_NO_DEVICE;
1443 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1444 return LIBUSB_ERROR_OTHER;
1447 /* update our cached active config descriptor */
1448 priv->active_config = config;
1450 return LIBUSB_SUCCESS;
1453 static int claim_interface(struct libusb_device_handle *handle, int iface)
1455 int fd = _device_handle_priv(handle)->fd;
1456 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1458 if (errno == ENOENT)
1459 return LIBUSB_ERROR_NOT_FOUND;
1460 else if (errno == EBUSY)
1461 return LIBUSB_ERROR_BUSY;
1462 else if (errno == ENODEV)
1463 return LIBUSB_ERROR_NO_DEVICE;
1465 usbi_err(HANDLE_CTX(handle),
1466 "claim interface failed, error %d errno %d", r, errno);
1467 return LIBUSB_ERROR_OTHER;
1472 static int release_interface(struct libusb_device_handle *handle, int iface)
1474 int fd = _device_handle_priv(handle)->fd;
1475 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1477 if (errno == ENODEV)
1478 return LIBUSB_ERROR_NO_DEVICE;
1480 usbi_err(HANDLE_CTX(handle),
1481 "release interface failed, error %d errno %d", r, errno);
1482 return LIBUSB_ERROR_OTHER;
1487 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1490 int fd = _device_handle_priv(handle)->fd;
1491 struct usbfs_setinterface setintf;
1494 setintf.interface = iface;
1495 setintf.altsetting = altsetting;
1496 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1498 if (errno == EINVAL)
1499 return LIBUSB_ERROR_NOT_FOUND;
1500 else if (errno == ENODEV)
1501 return LIBUSB_ERROR_NO_DEVICE;
1503 usbi_err(HANDLE_CTX(handle),
1504 "setintf failed error %d errno %d", r, errno);
1505 return LIBUSB_ERROR_OTHER;
1511 static int op_clear_halt(struct libusb_device_handle *handle,
1512 unsigned char endpoint)
1514 int fd = _device_handle_priv(handle)->fd;
1515 unsigned int _endpoint = endpoint;
1516 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1518 if (errno == ENOENT)
1519 return LIBUSB_ERROR_NOT_FOUND;
1520 else if (errno == ENODEV)
1521 return LIBUSB_ERROR_NO_DEVICE;
1523 usbi_err(HANDLE_CTX(handle),
1524 "clear_halt failed error %d errno %d", r, errno);
1525 return LIBUSB_ERROR_OTHER;
1531 static int op_reset_device(struct libusb_device_handle *handle)
1533 int fd = _device_handle_priv(handle)->fd;
1536 /* Doing a device reset will cause the usbfs driver to get unbound
1537 from any interfaces it is bound to. By voluntarily unbinding
1538 the usbfs driver ourself, we stop the kernel from rebinding
1539 the interface after reset (which would end up with the interface
1540 getting bound to the in kernel driver if any). */
1541 for (i = 0; i < USB_MAXINTERFACES; i++) {
1542 if (handle->claimed_interfaces & (1L << i)) {
1543 release_interface(handle, i);
1547 usbi_mutex_lock(&handle->lock);
1548 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1550 if (errno == ENODEV) {
1551 ret = LIBUSB_ERROR_NOT_FOUND;
1555 usbi_err(HANDLE_CTX(handle),
1556 "reset failed error %d errno %d", r, errno);
1557 ret = LIBUSB_ERROR_OTHER;
1561 /* And re-claim any interfaces which were claimed before the reset */
1562 for (i = 0; i < USB_MAXINTERFACES; i++) {
1563 if (handle->claimed_interfaces & (1L << i)) {
1565 * A driver may have completed modprobing during
1566 * IOCTL_USBFS_RESET, and bound itself as soon as
1567 * IOCTL_USBFS_RESET released the device lock
1569 r = detach_kernel_driver_and_claim(handle, i);
1571 usbi_warn(HANDLE_CTX(handle),
1572 "failed to re-claim interface %d after reset: %s",
1573 i, libusb_error_name(r));
1574 handle->claimed_interfaces &= ~(1L << i);
1575 ret = LIBUSB_ERROR_NOT_FOUND;
1580 usbi_mutex_unlock(&handle->lock);
1584 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1585 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1587 int r, fd = _device_handle_priv(handle)->fd;
1588 struct usbfs_streams *streams;
1590 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1591 return LIBUSB_ERROR_INVALID_PARAM;
1593 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1595 return LIBUSB_ERROR_NO_MEM;
1597 streams->num_streams = num_streams;
1598 streams->num_eps = num_endpoints;
1599 memcpy(streams->eps, endpoints, num_endpoints);
1601 r = ioctl(fd, req, streams);
1606 if (errno == ENOTTY)
1607 return LIBUSB_ERROR_NOT_SUPPORTED;
1608 else if (errno == EINVAL)
1609 return LIBUSB_ERROR_INVALID_PARAM;
1610 else if (errno == ENODEV)
1611 return LIBUSB_ERROR_NO_DEVICE;
1613 usbi_err(HANDLE_CTX(handle),
1614 "streams-ioctl failed error %d errno %d", r, errno);
1615 return LIBUSB_ERROR_OTHER;
1620 static int op_alloc_streams(struct libusb_device_handle *handle,
1621 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1623 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1624 num_streams, endpoints, num_endpoints);
1627 static int op_free_streams(struct libusb_device_handle *handle,
1628 unsigned char *endpoints, int num_endpoints)
1630 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1631 endpoints, num_endpoints);
1634 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1637 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1638 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1639 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1640 if (buffer == MAP_FAILED) {
1641 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1648 static int op_dev_mem_free(struct libusb_device_handle *handle,
1649 unsigned char *buffer, size_t len)
1651 if (munmap(buffer, len) != 0) {
1652 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1654 return LIBUSB_ERROR_OTHER;
1656 return LIBUSB_SUCCESS;
1660 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1663 int fd = _device_handle_priv(handle)->fd;
1664 struct usbfs_getdriver getdrv;
1667 getdrv.interface = interface;
1668 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1670 if (errno == ENODATA)
1672 else if (errno == ENODEV)
1673 return LIBUSB_ERROR_NO_DEVICE;
1675 usbi_err(HANDLE_CTX(handle),
1676 "get driver failed error %d errno %d", r, errno);
1677 return LIBUSB_ERROR_OTHER;
1680 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1683 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1686 int fd = _device_handle_priv(handle)->fd;
1687 struct usbfs_ioctl command;
1688 struct usbfs_getdriver getdrv;
1691 command.ifno = interface;
1692 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1693 command.data = NULL;
1695 getdrv.interface = interface;
1696 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1697 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1698 return LIBUSB_ERROR_NOT_FOUND;
1700 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1702 if (errno == ENODATA)
1703 return LIBUSB_ERROR_NOT_FOUND;
1704 else if (errno == EINVAL)
1705 return LIBUSB_ERROR_INVALID_PARAM;
1706 else if (errno == ENODEV)
1707 return LIBUSB_ERROR_NO_DEVICE;
1709 usbi_err(HANDLE_CTX(handle),
1710 "detach failed error %d errno %d", r, errno);
1711 return LIBUSB_ERROR_OTHER;
1717 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1720 int fd = _device_handle_priv(handle)->fd;
1721 struct usbfs_ioctl command;
1724 command.ifno = interface;
1725 command.ioctl_code = IOCTL_USBFS_CONNECT;
1726 command.data = NULL;
1728 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1730 if (errno == ENODATA)
1731 return LIBUSB_ERROR_NOT_FOUND;
1732 else if (errno == EINVAL)
1733 return LIBUSB_ERROR_INVALID_PARAM;
1734 else if (errno == ENODEV)
1735 return LIBUSB_ERROR_NO_DEVICE;
1736 else if (errno == EBUSY)
1737 return LIBUSB_ERROR_BUSY;
1739 usbi_err(HANDLE_CTX(handle),
1740 "attach failed error %d errno %d", r, errno);
1741 return LIBUSB_ERROR_OTHER;
1742 } else if (r == 0) {
1743 return LIBUSB_ERROR_NOT_FOUND;
1749 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1752 struct usbfs_disconnect_claim dc;
1753 int r, fd = _device_handle_priv(handle)->fd;
1755 dc.interface = interface;
1756 strcpy(dc.driver, "usbfs");
1757 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1758 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1759 if (r != 0 && errno != ENOTTY) {
1762 return LIBUSB_ERROR_BUSY;
1764 return LIBUSB_ERROR_INVALID_PARAM;
1766 return LIBUSB_ERROR_NO_DEVICE;
1768 usbi_err(HANDLE_CTX(handle),
1769 "disconnect-and-claim failed errno %d", errno);
1770 return LIBUSB_ERROR_OTHER;
1774 /* Fallback code for kernels which don't support the
1775 disconnect-and-claim ioctl */
1776 r = op_detach_kernel_driver(handle, interface);
1777 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1780 return claim_interface(handle, interface);
1783 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1785 if (handle->auto_detach_kernel_driver)
1786 return detach_kernel_driver_and_claim(handle, iface);
1788 return claim_interface(handle, iface);
1791 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1795 r = release_interface(handle, iface);
1799 if (handle->auto_detach_kernel_driver)
1800 op_attach_kernel_driver(handle, iface);
1805 static void op_destroy_device(struct libusb_device *dev)
1807 struct linux_device_priv *priv = _device_priv(dev);
1808 if (priv->descriptors)
1809 free(priv->descriptors);
1810 if (priv->sysfs_dir)
1811 free(priv->sysfs_dir);
1814 /* URBs are discarded in reverse order of submission to avoid races. */
1815 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1817 struct libusb_transfer *transfer =
1818 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1819 struct linux_transfer_priv *tpriv =
1820 usbi_transfer_get_os_priv(itransfer);
1821 struct linux_device_handle_priv *dpriv =
1822 _device_handle_priv(transfer->dev_handle);
1824 struct usbfs_urb *urb;
1826 for (i = last_plus_one - 1; i >= first; i--) {
1827 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1828 urb = tpriv->iso_urbs[i];
1830 urb = &tpriv->urbs[i];
1832 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1835 if (EINVAL == errno) {
1836 usbi_dbg("URB not found --> assuming ready to be reaped");
1837 if (i == (last_plus_one - 1))
1838 ret = LIBUSB_ERROR_NOT_FOUND;
1839 } else if (ENODEV == errno) {
1840 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1841 ret = LIBUSB_ERROR_NO_DEVICE;
1843 usbi_warn(TRANSFER_CTX(transfer),
1844 "unrecognised discard errno %d", errno);
1845 ret = LIBUSB_ERROR_OTHER;
1851 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1854 for (i = 0; i < tpriv->num_urbs; i++) {
1855 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1861 free(tpriv->iso_urbs);
1862 tpriv->iso_urbs = NULL;
1865 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1867 struct libusb_transfer *transfer =
1868 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1869 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1870 struct linux_device_handle_priv *dpriv =
1871 _device_handle_priv(transfer->dev_handle);
1872 struct usbfs_urb *urbs;
1873 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1874 == LIBUSB_ENDPOINT_OUT;
1875 int bulk_buffer_len, use_bulk_continuation;
1879 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1880 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1881 return LIBUSB_ERROR_NOT_SUPPORTED;
1884 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1885 * around this by splitting large transfers into 16k blocks, and then
1886 * submit all urbs at once. it would be simpler to submit one urb at
1887 * a time, but there is a big performance gain doing it this way.
1889 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1890 * using arbritary large transfers can still be a bad idea though, as
1891 * the kernel needs to allocate physical contiguous memory for this,
1892 * which may fail for large buffers.
1894 * The kernel solves this problem by splitting the transfer into
1895 * blocks itself when the host-controller is scatter-gather capable
1896 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1898 * Last, there is the issue of short-transfers when splitting, for
1899 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1900 * is needed, but this is not always available.
1902 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1903 /* Good! Just submit everything in one go */
1904 bulk_buffer_len = transfer->length ? transfer->length : 1;
1905 use_bulk_continuation = 0;
1906 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1907 /* Split the transfers and use bulk-continuation to
1908 avoid issues with short-transfers */
1909 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1910 use_bulk_continuation = 1;
1911 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1912 /* Don't split, assume the kernel can alloc the buffer
1913 (otherwise the submit will fail with -ENOMEM) */
1914 bulk_buffer_len = transfer->length ? transfer->length : 1;
1915 use_bulk_continuation = 0;
1917 /* Bad, splitting without bulk-continuation, short transfers
1918 which end before the last urb will not work reliable! */
1919 /* Note we don't warn here as this is "normal" on kernels <
1920 2.6.32 and not a problem for most applications */
1921 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1922 use_bulk_continuation = 0;
1925 int num_urbs = transfer->length / bulk_buffer_len;
1926 int last_urb_partial = 0;
1928 if (transfer->length == 0) {
1930 } else if ((transfer->length % bulk_buffer_len) > 0) {
1931 last_urb_partial = 1;
1934 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1936 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1938 return LIBUSB_ERROR_NO_MEM;
1940 tpriv->num_urbs = num_urbs;
1941 tpriv->num_retired = 0;
1942 tpriv->reap_action = NORMAL;
1943 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1945 for (i = 0; i < num_urbs; i++) {
1946 struct usbfs_urb *urb = &urbs[i];
1947 urb->usercontext = itransfer;
1948 switch (transfer->type) {
1949 case LIBUSB_TRANSFER_TYPE_BULK:
1950 urb->type = USBFS_URB_TYPE_BULK;
1953 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1954 urb->type = USBFS_URB_TYPE_BULK;
1955 urb->stream_id = itransfer->stream_id;
1957 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1958 urb->type = USBFS_URB_TYPE_INTERRUPT;
1961 urb->endpoint = transfer->endpoint;
1962 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1963 /* don't set the short not ok flag for the last URB */
1964 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1965 urb->flags = USBFS_URB_SHORT_NOT_OK;
1966 if (i == num_urbs - 1 && last_urb_partial)
1967 urb->buffer_length = transfer->length % bulk_buffer_len;
1968 else if (transfer->length == 0)
1969 urb->buffer_length = 0;
1971 urb->buffer_length = bulk_buffer_len;
1973 if (i > 0 && use_bulk_continuation)
1974 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1976 /* we have already checked that the flag is supported */
1977 if (is_out && i == num_urbs - 1 &&
1978 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1979 urb->flags |= USBFS_URB_ZERO_PACKET;
1981 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1983 if (errno == ENODEV) {
1984 r = LIBUSB_ERROR_NO_DEVICE;
1986 usbi_err(TRANSFER_CTX(transfer),
1987 "submiturb failed error %d errno=%d", r, errno);
1988 r = LIBUSB_ERROR_IO;
1991 /* if the first URB submission fails, we can simply free up and
1992 * return failure immediately. */
1994 usbi_dbg("first URB failed, easy peasy");
2000 /* if it's not the first URB that failed, the situation is a bit
2001 * tricky. we may need to discard all previous URBs. there are
2003 * - discarding is asynchronous - discarded urbs will be reaped
2004 * later. the user must not have freed the transfer when the
2005 * discarded URBs are reaped, otherwise libusb will be using
2007 * - the earlier URBs may have completed successfully and we do
2008 * not want to throw away any data.
2009 * - this URB failing may be no error; EREMOTEIO means that
2010 * this transfer simply didn't need all the URBs we submitted
2011 * so, we report that the transfer was submitted successfully and
2012 * in case of error we discard all previous URBs. later when
2013 * the final reap completes we can report error to the user,
2014 * or success if an earlier URB was completed successfully.
2016 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2018 /* The URBs we haven't submitted yet we count as already
2020 tpriv->num_retired += num_urbs - i;
2022 /* If we completed short then don't try to discard. */
2023 if (COMPLETED_EARLY == tpriv->reap_action)
2026 discard_urbs(itransfer, 0, i);
2028 usbi_dbg("reporting successful submission but waiting for %d "
2029 "discards before reporting error", i);
2037 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2039 struct libusb_transfer *transfer =
2040 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2041 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2042 struct linux_device_handle_priv *dpriv =
2043 _device_handle_priv(transfer->dev_handle);
2044 struct usbfs_urb **urbs;
2045 int num_packets = transfer->num_iso_packets;
2046 int num_packets_remaining;
2049 unsigned int packet_len;
2050 unsigned int total_len = 0;
2051 unsigned char *urb_buffer = transfer->buffer;
2053 if (num_packets < 1)
2054 return LIBUSB_ERROR_INVALID_PARAM;
2056 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2057 * at least three times, but we attempt to detect this limit during
2058 * init and check it here. if the kernel rejects the request due to
2059 * its size, we return an error indicating such to the user.
2061 for (i = 0; i < num_packets; i++) {
2062 packet_len = transfer->iso_packet_desc[i].length;
2064 if (packet_len > max_iso_packet_len) {
2065 usbi_warn(TRANSFER_CTX(transfer),
2066 "iso packet length of %u bytes exceeds maximum of %u bytes",
2067 packet_len, max_iso_packet_len);
2068 return LIBUSB_ERROR_INVALID_PARAM;
2071 total_len += packet_len;
2074 if (transfer->length < (int)total_len)
2075 return LIBUSB_ERROR_INVALID_PARAM;
2077 /* usbfs limits the number of iso packets per URB */
2078 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2080 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2083 urbs = calloc(num_urbs, sizeof(*urbs));
2085 return LIBUSB_ERROR_NO_MEM;
2087 tpriv->iso_urbs = urbs;
2088 tpriv->num_urbs = num_urbs;
2089 tpriv->num_retired = 0;
2090 tpriv->reap_action = NORMAL;
2091 tpriv->iso_packet_offset = 0;
2093 /* allocate + initialize each URB with the correct number of packets */
2094 num_packets_remaining = num_packets;
2095 for (i = 0, j = 0; i < num_urbs; i++) {
2096 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2097 struct usbfs_urb *urb;
2101 alloc_size = sizeof(*urb)
2102 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2103 urb = calloc(1, alloc_size);
2105 free_iso_urbs(tpriv);
2106 return LIBUSB_ERROR_NO_MEM;
2110 /* populate packet lengths */
2111 for (k = 0; k < num_packets_in_urb; j++, k++) {
2112 packet_len = transfer->iso_packet_desc[j].length;
2113 urb->buffer_length += packet_len;
2114 urb->iso_frame_desc[k].length = packet_len;
2117 urb->usercontext = itransfer;
2118 urb->type = USBFS_URB_TYPE_ISO;
2119 /* FIXME: interface for non-ASAP data? */
2120 urb->flags = USBFS_URB_ISO_ASAP;
2121 urb->endpoint = transfer->endpoint;
2122 urb->number_of_packets = num_packets_in_urb;
2123 urb->buffer = urb_buffer;
2125 urb_buffer += urb->buffer_length;
2126 num_packets_remaining -= num_packets_in_urb;
2130 for (i = 0; i < num_urbs; i++) {
2131 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2133 if (errno == ENODEV) {
2134 r = LIBUSB_ERROR_NO_DEVICE;
2135 } else if (errno == EINVAL) {
2136 usbi_warn(TRANSFER_CTX(transfer),
2137 "submiturb failed, transfer too large");
2138 r = LIBUSB_ERROR_INVALID_PARAM;
2139 } else if (errno == EMSGSIZE) {
2140 usbi_warn(TRANSFER_CTX(transfer),
2141 "submiturb failed, iso packet length too large");
2142 r = LIBUSB_ERROR_INVALID_PARAM;
2144 usbi_err(TRANSFER_CTX(transfer),
2145 "submiturb failed error %d errno=%d", r, errno);
2146 r = LIBUSB_ERROR_IO;
2149 /* if the first URB submission fails, we can simply free up and
2150 * return failure immediately. */
2152 usbi_dbg("first URB failed, easy peasy");
2153 free_iso_urbs(tpriv);
2157 /* if it's not the first URB that failed, the situation is a bit
2158 * tricky. we must discard all previous URBs. there are
2160 * - discarding is asynchronous - discarded urbs will be reaped
2161 * later. the user must not have freed the transfer when the
2162 * discarded URBs are reaped, otherwise libusb will be using
2164 * - the earlier URBs may have completed successfully and we do
2165 * not want to throw away any data.
2166 * so, in this case we discard all the previous URBs BUT we report
2167 * that the transfer was submitted successfully. then later when
2168 * the final discard completes we can report error to the user.
2170 tpriv->reap_action = SUBMIT_FAILED;
2172 /* The URBs we haven't submitted yet we count as already
2174 tpriv->num_retired = num_urbs - i;
2175 discard_urbs(itransfer, 0, i);
2177 usbi_dbg("reporting successful submission but waiting for %d "
2178 "discards before reporting error", i);
2186 static int submit_control_transfer(struct usbi_transfer *itransfer)
2188 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2189 struct libusb_transfer *transfer =
2190 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2191 struct linux_device_handle_priv *dpriv =
2192 _device_handle_priv(transfer->dev_handle);
2193 struct usbfs_urb *urb;
2196 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2197 return LIBUSB_ERROR_INVALID_PARAM;
2199 urb = calloc(1, sizeof(struct usbfs_urb));
2201 return LIBUSB_ERROR_NO_MEM;
2203 tpriv->num_urbs = 1;
2204 tpriv->reap_action = NORMAL;
2206 urb->usercontext = itransfer;
2207 urb->type = USBFS_URB_TYPE_CONTROL;
2208 urb->endpoint = transfer->endpoint;
2209 urb->buffer = transfer->buffer;
2210 urb->buffer_length = transfer->length;
2212 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2216 if (errno == ENODEV)
2217 return LIBUSB_ERROR_NO_DEVICE;
2219 usbi_err(TRANSFER_CTX(transfer),
2220 "submiturb failed error %d errno=%d", r, errno);
2221 return LIBUSB_ERROR_IO;
2226 static int op_submit_transfer(struct usbi_transfer *itransfer)
2228 struct libusb_transfer *transfer =
2229 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2231 switch (transfer->type) {
2232 case LIBUSB_TRANSFER_TYPE_CONTROL:
2233 return submit_control_transfer(itransfer);
2234 case LIBUSB_TRANSFER_TYPE_BULK:
2235 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2236 return submit_bulk_transfer(itransfer);
2237 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2238 return submit_bulk_transfer(itransfer);
2239 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2240 return submit_iso_transfer(itransfer);
2242 usbi_err(TRANSFER_CTX(transfer),
2243 "unknown endpoint type %d", transfer->type);
2244 return LIBUSB_ERROR_INVALID_PARAM;
2248 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2250 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2251 struct libusb_transfer *transfer =
2252 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2256 return LIBUSB_ERROR_NOT_FOUND;
2258 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2262 switch (transfer->type) {
2263 case LIBUSB_TRANSFER_TYPE_BULK:
2264 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2265 if (tpriv->reap_action == ERROR)
2267 /* else, fall through */
2269 tpriv->reap_action = CANCELLED;
2275 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2277 struct libusb_transfer *transfer =
2278 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2279 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2281 switch (transfer->type) {
2282 case LIBUSB_TRANSFER_TYPE_CONTROL:
2283 case LIBUSB_TRANSFER_TYPE_BULK:
2284 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2285 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2291 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2292 if (tpriv->iso_urbs) {
2293 free_iso_urbs(tpriv);
2294 tpriv->iso_urbs = NULL;
2298 usbi_err(TRANSFER_CTX(transfer),
2299 "unknown endpoint type %d", transfer->type);
2303 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2304 struct usbfs_urb *urb)
2306 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2307 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2308 int urb_idx = urb - tpriv->urbs;
2310 usbi_mutex_lock(&itransfer->lock);
2311 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2312 urb_idx + 1, tpriv->num_urbs);
2314 tpriv->num_retired++;
2316 if (tpriv->reap_action != NORMAL) {
2317 /* cancelled, submit_fail, or completed early */
2318 usbi_dbg("abnormal reap: urb status %d", urb->status);
2320 /* even though we're in the process of cancelling, it's possible that
2321 * we may receive some data in these URBs that we don't want to lose.
2323 * 1. while the kernel is cancelling all the packets that make up an
2324 * URB, a few of them might complete. so we get back a successful
2325 * cancellation *and* some data.
2326 * 2. we receive a short URB which marks the early completion condition,
2327 * so we start cancelling the remaining URBs. however, we're too
2328 * slow and another URB completes (or at least completes partially).
2329 * (this can't happen since we always use BULK_CONTINUATION.)
2331 * When this happens, our objectives are not to lose any "surplus" data,
2332 * and also to stick it at the end of the previously-received data
2333 * (closing any holes), so that libusb reports the total amount of
2334 * transferred data and presents it in a contiguous chunk.
2336 if (urb->actual_length > 0) {
2337 unsigned char *target = transfer->buffer + itransfer->transferred;
2338 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2339 if (urb->buffer != target) {
2340 usbi_dbg("moving surplus data from offset %d to offset %d",
2341 (unsigned char *) urb->buffer - transfer->buffer,
2342 target - transfer->buffer);
2343 memmove(target, urb->buffer, urb->actual_length);
2345 itransfer->transferred += urb->actual_length;
2348 if (tpriv->num_retired == tpriv->num_urbs) {
2349 usbi_dbg("abnormal reap: last URB handled, reporting");
2350 if (tpriv->reap_action != COMPLETED_EARLY &&
2351 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2352 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2358 itransfer->transferred += urb->actual_length;
2360 /* Many of these errors can occur on *any* urb of a multi-urb
2361 * transfer. When they do, we tear down the rest of the transfer.
2363 switch (urb->status) {
2366 case -EREMOTEIO: /* short transfer */
2368 case -ENOENT: /* cancelled */
2373 usbi_dbg("device removed");
2374 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2375 goto cancel_remaining;
2377 usbi_dbg("detected endpoint stall");
2378 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2379 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2380 goto cancel_remaining;
2382 /* overflow can only ever occur in the last urb */
2383 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2384 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2385 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2392 usbi_dbg("low level error %d", urb->status);
2393 tpriv->reap_action = ERROR;
2394 goto cancel_remaining;
2396 usbi_warn(ITRANSFER_CTX(itransfer),
2397 "unrecognised urb status %d", urb->status);
2398 tpriv->reap_action = ERROR;
2399 goto cancel_remaining;
2402 /* if we're the last urb or we got less data than requested then we're
2404 if (urb_idx == tpriv->num_urbs - 1) {
2405 usbi_dbg("last URB in transfer --> complete!");
2407 } else if (urb->actual_length < urb->buffer_length) {
2408 usbi_dbg("short transfer %d/%d --> complete!",
2409 urb->actual_length, urb->buffer_length);
2410 if (tpriv->reap_action == NORMAL)
2411 tpriv->reap_action = COMPLETED_EARLY;
2416 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2417 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2419 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2422 /* cancel remaining urbs and wait for their completion before
2423 * reporting results */
2424 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2427 usbi_mutex_unlock(&itransfer->lock);
2433 usbi_mutex_unlock(&itransfer->lock);
2434 return CANCELLED == tpriv->reap_action ?
2435 usbi_handle_transfer_cancellation(itransfer) :
2436 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2439 static int handle_iso_completion(struct usbi_transfer *itransfer,
2440 struct usbfs_urb *urb)
2442 struct libusb_transfer *transfer =
2443 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2444 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2445 int num_urbs = tpriv->num_urbs;
2448 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2450 usbi_mutex_lock(&itransfer->lock);
2451 for (i = 0; i < num_urbs; i++) {
2452 if (urb == tpriv->iso_urbs[i]) {
2458 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2459 usbi_mutex_unlock(&itransfer->lock);
2460 return LIBUSB_ERROR_NOT_FOUND;
2463 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2466 /* copy isochronous results back in */
2468 for (i = 0; i < urb->number_of_packets; i++) {
2469 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2470 struct libusb_iso_packet_descriptor *lib_desc =
2471 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2472 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2473 switch (urb_desc->status) {
2476 case -ENOENT: /* cancelled */
2481 usbi_dbg("device removed");
2482 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2485 usbi_dbg("detected endpoint stall");
2486 lib_desc->status = LIBUSB_TRANSFER_STALL;
2489 usbi_dbg("overflow error");
2490 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2498 usbi_dbg("low-level USB error %d", urb_desc->status);
2499 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2502 usbi_warn(TRANSFER_CTX(transfer),
2503 "unrecognised urb status %d", urb_desc->status);
2504 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2507 lib_desc->actual_length = urb_desc->actual_length;
2510 tpriv->num_retired++;
2512 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2513 usbi_dbg("CANCEL: urb status %d", urb->status);
2515 if (tpriv->num_retired == num_urbs) {
2516 usbi_dbg("CANCEL: last URB handled, reporting");
2517 free_iso_urbs(tpriv);
2518 if (tpriv->reap_action == CANCELLED) {
2519 usbi_mutex_unlock(&itransfer->lock);
2520 return usbi_handle_transfer_cancellation(itransfer);
2522 usbi_mutex_unlock(&itransfer->lock);
2523 return usbi_handle_transfer_completion(itransfer,
2524 LIBUSB_TRANSFER_ERROR);
2530 switch (urb->status) {
2533 case -ENOENT: /* cancelled */
2537 usbi_dbg("device removed");
2538 status = LIBUSB_TRANSFER_NO_DEVICE;
2541 usbi_warn(TRANSFER_CTX(transfer),
2542 "unrecognised urb status %d", urb->status);
2543 status = LIBUSB_TRANSFER_ERROR;
2547 /* if we're the last urb then we're done */
2548 if (urb_idx == num_urbs) {
2549 usbi_dbg("last URB in transfer --> complete!");
2550 free_iso_urbs(tpriv);
2551 usbi_mutex_unlock(&itransfer->lock);
2552 return usbi_handle_transfer_completion(itransfer, status);
2556 usbi_mutex_unlock(&itransfer->lock);
2560 static int handle_control_completion(struct usbi_transfer *itransfer,
2561 struct usbfs_urb *urb)
2563 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2566 usbi_mutex_lock(&itransfer->lock);
2567 usbi_dbg("handling completion status %d", urb->status);
2569 itransfer->transferred += urb->actual_length;
2571 if (tpriv->reap_action == CANCELLED) {
2572 if (urb->status != 0 && urb->status != -ENOENT)
2573 usbi_warn(ITRANSFER_CTX(itransfer),
2574 "cancel: unrecognised urb status %d", urb->status);
2577 usbi_mutex_unlock(&itransfer->lock);
2578 return usbi_handle_transfer_cancellation(itransfer);
2581 switch (urb->status) {
2583 status = LIBUSB_TRANSFER_COMPLETED;
2585 case -ENOENT: /* cancelled */
2586 status = LIBUSB_TRANSFER_CANCELLED;
2590 usbi_dbg("device removed");
2591 status = LIBUSB_TRANSFER_NO_DEVICE;
2594 usbi_dbg("unsupported control request");
2595 status = LIBUSB_TRANSFER_STALL;
2598 usbi_dbg("control overflow error");
2599 status = LIBUSB_TRANSFER_OVERFLOW;
2606 usbi_dbg("low-level bus error occurred");
2607 status = LIBUSB_TRANSFER_ERROR;
2610 usbi_warn(ITRANSFER_CTX(itransfer),
2611 "unrecognised urb status %d", urb->status);
2612 status = LIBUSB_TRANSFER_ERROR;
2618 usbi_mutex_unlock(&itransfer->lock);
2619 return usbi_handle_transfer_completion(itransfer, status);
2622 static int reap_for_handle(struct libusb_device_handle *handle)
2624 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2626 struct usbfs_urb *urb;
2627 struct usbi_transfer *itransfer;
2628 struct libusb_transfer *transfer;
2630 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2631 if (r == -1 && errno == EAGAIN)
2634 if (errno == ENODEV)
2635 return LIBUSB_ERROR_NO_DEVICE;
2637 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2639 return LIBUSB_ERROR_IO;
2642 itransfer = urb->usercontext;
2643 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2645 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2646 urb->actual_length);
2648 switch (transfer->type) {
2649 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2650 return handle_iso_completion(itransfer, urb);
2651 case LIBUSB_TRANSFER_TYPE_BULK:
2652 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2653 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2654 return handle_bulk_completion(itransfer, urb);
2655 case LIBUSB_TRANSFER_TYPE_CONTROL:
2656 return handle_control_completion(itransfer, urb);
2658 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2660 return LIBUSB_ERROR_OTHER;
2664 static int op_handle_events(struct libusb_context *ctx,
2665 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2670 usbi_mutex_lock(&ctx->open_devs_lock);
2671 for (i = 0; i < nfds && num_ready > 0; i++) {
2672 struct pollfd *pollfd = &fds[i];
2673 struct libusb_device_handle *handle;
2674 struct linux_device_handle_priv *hpriv = NULL;
2676 if (!pollfd->revents)
2680 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2681 hpriv = _device_handle_priv(handle);
2682 if (hpriv->fd == pollfd->fd)
2686 if (!hpriv || hpriv->fd != pollfd->fd) {
2687 usbi_err(ctx, "cannot find handle for fd %d",
2692 if (pollfd->revents & POLLERR) {
2693 /* remove the fd from the pollfd set so that it doesn't continuously
2694 * trigger an event, and flag that it has been removed so op_close()
2695 * doesn't try to remove it a second time */
2696 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2697 hpriv->fd_removed = 1;
2699 /* device will still be marked as attached if hotplug monitor thread
2700 * hasn't processed remove event yet */
2701 usbi_mutex_static_lock(&linux_hotplug_lock);
2702 if (handle->dev->attached)
2703 linux_device_disconnected(handle->dev->bus_number,
2704 handle->dev->device_address);
2705 usbi_mutex_static_unlock(&linux_hotplug_lock);
2707 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2709 r = reap_for_handle(handle);
2713 usbi_handle_disconnect(handle);
2718 r = reap_for_handle(handle);
2720 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2728 usbi_mutex_unlock(&ctx->open_devs_lock);
2732 static int op_clock_gettime(int clk_id, struct timespec *tp)
2735 case USBI_CLOCK_MONOTONIC:
2736 return clock_gettime(monotonic_clkid, tp);
2737 case USBI_CLOCK_REALTIME:
2738 return clock_gettime(CLOCK_REALTIME, tp);
2740 return LIBUSB_ERROR_INVALID_PARAM;
2744 #ifdef USBI_TIMERFD_AVAILABLE
2745 static clockid_t op_get_timerfd_clockid(void)
2747 return monotonic_clkid;
2752 const struct usbi_os_backend usbi_backend = {
2753 .name = "Linux usbfs",
2754 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2757 .get_device_list = NULL,
2758 .hotplug_poll = op_hotplug_poll,
2759 .get_device_descriptor = op_get_device_descriptor,
2760 .get_active_config_descriptor = op_get_active_config_descriptor,
2761 .get_config_descriptor = op_get_config_descriptor,
2762 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2766 .get_configuration = op_get_configuration,
2767 .set_configuration = op_set_configuration,
2768 .claim_interface = op_claim_interface,
2769 .release_interface = op_release_interface,
2771 .set_interface_altsetting = op_set_interface,
2772 .clear_halt = op_clear_halt,
2773 .reset_device = op_reset_device,
2775 .alloc_streams = op_alloc_streams,
2776 .free_streams = op_free_streams,
2778 .dev_mem_alloc = op_dev_mem_alloc,
2779 .dev_mem_free = op_dev_mem_free,
2781 .kernel_driver_active = op_kernel_driver_active,
2782 .detach_kernel_driver = op_detach_kernel_driver,
2783 .attach_kernel_driver = op_attach_kernel_driver,
2785 .destroy_device = op_destroy_device,
2787 .submit_transfer = op_submit_transfer,
2788 .cancel_transfer = op_cancel_transfer,
2789 .clear_transfer_priv = op_clear_transfer_priv,
2791 .handle_events = op_handle_events,
2793 .clock_gettime = op_clock_gettime,
2795 #ifdef USBI_TIMERFD_AVAILABLE
2796 .get_timerfd_clockid = op_get_timerfd_clockid,
2799 .device_priv_size = sizeof(struct linux_device_priv),
2800 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2801 .transfer_priv_size = sizeof(struct linux_transfer_priv),