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>
37 #include <sys/types.h>
38 #include <sys/utsname.h>
42 #include "linux_usbfs.h"
45 * opening a usbfs node causes the device to be resumed, so we attempt to
46 * avoid this during enumeration.
48 * sysfs allows us to read the kernel's in-memory copies of device descriptors
49 * and so forth, avoiding the need to open the device:
50 * - The binary "descriptors" file contains all config descriptors since
51 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
52 * - The binary "descriptors" file was added in 2.6.23, commit
53 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
54 * active config descriptors
55 * - The "busnum" file was added in 2.6.22, commit
56 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
57 * - The "devnum" file has been present since pre-2.6.18
58 * - the "bConfigurationValue" file has been present since pre-2.6.18
60 * If we have bConfigurationValue, busnum, and devnum, then we can determine
61 * the active configuration without having to open the usbfs node in RDWR mode.
62 * The busnum file is important as that is the only way we can relate sysfs
63 * devices to usbfs nodes.
65 * If we also have all descriptors, we can obtain the device descriptor and
66 * configuration without touching usbfs at all.
69 /* endianness for multi-byte fields:
71 * Descriptors exposed by usbfs have the multi-byte fields in the device
72 * descriptor as host endian. Multi-byte fields in the other descriptors are
73 * bus-endian. The kernel documentation says otherwise, but it is wrong.
75 * In sysfs all descriptors are bus-endian.
78 static const char *usbfs_path = NULL;
80 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
81 static int usbdev_names = 0;
83 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
84 * allows us to mark URBs as being part of a specific logical transfer when
85 * we submit them to the kernel. then, on any error except a cancellation, all
86 * URBs within that transfer will be cancelled and no more URBs will be
87 * accepted for the transfer, meaning that no more data can creep in.
89 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
90 * (in either direction) except the first.
91 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
92 * last; it means that the kernel should treat a short reply as an error.
93 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
94 * transfers can't be short unless there's already some sort of error), and
95 * setting this flag is disallowed (a kernel with USB debugging enabled will
98 static int supports_flag_bulk_continuation = -1;
100 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
101 * allows us to mark URBs that should be followed by a zero length data
102 * packet, which can be required by device- or class-specific protocols.
104 static int supports_flag_zero_packet = -1;
106 /* clock ID for monotonic clock, as not all clock sources are available on all
107 * systems. appropriate choice made at initialization time. */
108 static clockid_t monotonic_clkid = -1;
110 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
111 * to sysfs, so we can relate devices. This also implies that we can read
112 * the active configuration through bConfigurationValue */
113 static int sysfs_can_relate_devices = -1;
115 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
116 * config descriptors (rather then just the active config) to the sysfs
117 * descriptors file, so from then on we can use them. */
118 static int sysfs_has_descriptors = -1;
120 /* how many times have we initted (and not exited) ? */
121 static int init_count = 0;
123 /* Serialize hotplug start/stop */
124 usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
125 /* Serialize scan-devices, event-thread, and poll */
126 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
128 static int linux_start_event_monitor(void);
129 static int linux_stop_event_monitor(void);
130 static int linux_scan_devices(struct libusb_context *ctx);
131 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
132 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
134 #if !defined(USE_UDEV)
135 static int linux_default_scan_devices (struct libusb_context *ctx);
138 struct linux_device_priv {
140 unsigned char *descriptors;
142 int active_config; /* cache val for !sysfs_can_relate_devices */
145 struct linux_device_handle_priv {
153 /* submission failed after the first URB, so await cancellation/completion
154 * of all the others */
157 /* cancelled by user or timeout */
160 /* completed multi-URB transfer in non-final URB */
163 /* one or more urbs encountered a low-level error */
167 struct linux_transfer_priv {
169 struct usbfs_urb *urbs;
170 struct usbfs_urb **iso_urbs;
173 enum reap_action reap_action;
176 enum libusb_transfer_status reap_status;
178 /* next iso packet in user-supplied transfer to be populated */
179 int iso_packet_offset;
182 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
184 struct libusb_context *ctx = DEVICE_CTX(dev);
190 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
191 usbfs_path, dev->bus_number, dev->device_address);
193 snprintf(path, PATH_MAX, "%s/%03d/%03d",
194 usbfs_path, dev->bus_number, dev->device_address);
196 fd = open(path, mode);
198 return fd; /* Success */
200 if (errno == ENOENT) {
202 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
204 /* Wait 10ms for USB device path creation.*/
207 fd = open(path, mode);
209 return fd; /* Success */
213 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
214 path, strerror(errno));
215 if (errno == EACCES && mode == O_RDWR)
216 usbi_err(ctx, "libusb requires write access to USB "
221 return LIBUSB_ERROR_ACCESS;
223 return LIBUSB_ERROR_NO_DEVICE;
224 return LIBUSB_ERROR_IO;
227 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
229 return (struct linux_device_priv *) dev->os_priv;
232 static struct linux_device_handle_priv *_device_handle_priv(
233 struct libusb_device_handle *handle)
235 return (struct linux_device_handle_priv *) handle->os_priv;
238 /* check dirent for a /dev/usbdev%d.%d name
239 * optionally return bus/device on success */
240 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
244 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
247 usbi_dbg("found: %s", entry->d_name);
255 static int check_usb_vfs(const char *dirname)
258 struct dirent *entry;
261 dir = opendir(dirname);
265 while ((entry = readdir(dir)) != NULL) {
266 if (entry->d_name[0] == '.')
269 /* We assume if we find any files that it must be the right place */
278 static const char *find_usbfs_path(void)
280 const char *path = "/dev/bus/usb";
281 const char *ret = NULL;
283 if (check_usb_vfs(path)) {
286 path = "/proc/bus/usb";
287 if (check_usb_vfs(path))
291 /* look for /dev/usbdev*.* if the normal places fail */
293 struct dirent *entry;
299 while ((entry = readdir(dir)) != NULL) {
300 if (_is_usbdev_entry(entry, NULL, NULL)) {
301 /* found one; that's enough */
311 /* On udev based systems without any usb-devices /dev/bus/usb will not
312 * exist. So if we've not found anything and we're using udev for hotplug
313 * simply assume /dev/bus/usb rather then making libusb_init fail. */
314 #if defined(USE_UDEV)
316 ret = "/dev/bus/usb";
320 usbi_dbg("found usbfs at %s", ret);
325 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
326 * seem to lack it). fall back to REALTIME if we have to. */
327 static clockid_t find_monotonic_clock(void)
329 #ifdef CLOCK_MONOTONIC
333 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
334 * because it's not available through timerfd */
335 r = clock_gettime(CLOCK_MONOTONIC, &ts);
337 return CLOCK_MONOTONIC;
338 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
341 return CLOCK_REALTIME;
344 static int kernel_version_ge(int major, int minor, int sublevel)
347 int atoms, kmajor, kminor, ksublevel;
351 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
360 /* kmajor == major */
362 return 0 == minor && 0 == sublevel;
368 /* kminor == minor */
370 return 0 == sublevel;
372 return ksublevel >= sublevel;
375 static int op_init(struct libusb_context *ctx)
380 usbfs_path = find_usbfs_path();
382 usbi_err(ctx, "could not find usbfs");
383 return LIBUSB_ERROR_OTHER;
386 if (monotonic_clkid == -1)
387 monotonic_clkid = find_monotonic_clock();
389 if (supports_flag_bulk_continuation == -1) {
390 /* bulk continuation URB flag available from Linux 2.6.32 */
391 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
392 if (supports_flag_bulk_continuation == -1) {
393 usbi_err(ctx, "error checking for bulk continuation support");
394 return LIBUSB_ERROR_OTHER;
398 if (supports_flag_bulk_continuation)
399 usbi_dbg("bulk continuation flag supported");
401 if (-1 == supports_flag_zero_packet) {
402 /* zero length packet URB flag fixed since Linux 2.6.31 */
403 supports_flag_zero_packet = kernel_version_ge(2,6,31);
404 if (-1 == supports_flag_zero_packet) {
405 usbi_err(ctx, "error checking for zero length packet support");
406 return LIBUSB_ERROR_OTHER;
410 if (supports_flag_zero_packet)
411 usbi_dbg("zero length packet flag supported");
413 if (-1 == sysfs_has_descriptors) {
414 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
415 sysfs_has_descriptors = kernel_version_ge(2,6,26);
416 if (-1 == sysfs_has_descriptors) {
417 usbi_err(ctx, "error checking for sysfs descriptors");
418 return LIBUSB_ERROR_OTHER;
422 if (-1 == sysfs_can_relate_devices) {
423 /* sysfs has busnum since Linux 2.6.22 */
424 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
425 if (-1 == sysfs_can_relate_devices) {
426 usbi_err(ctx, "error checking for sysfs busnum");
427 return LIBUSB_ERROR_OTHER;
431 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
432 r = stat(SYSFS_DEVICE_PATH, &statbuf);
433 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
434 usbi_warn(ctx, "sysfs not mounted");
435 sysfs_can_relate_devices = 0;
436 sysfs_has_descriptors = 0;
440 if (sysfs_can_relate_devices)
441 usbi_dbg("sysfs can relate devices");
443 if (sysfs_has_descriptors)
444 usbi_dbg("sysfs has complete descriptors");
446 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
448 if (init_count == 0) {
449 /* start up hotplug event handler */
450 r = linux_start_event_monitor();
452 if (r == LIBUSB_SUCCESS) {
453 r = linux_scan_devices(ctx);
454 if (r == LIBUSB_SUCCESS)
456 else if (init_count == 0)
457 linux_stop_event_monitor();
459 usbi_err(ctx, "error starting hotplug event monitor");
460 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
465 static void op_exit(void)
467 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
468 assert(init_count != 0);
470 /* tear down event handler */
471 (void)linux_stop_event_monitor();
473 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
476 static int linux_start_event_monitor(void)
478 #if defined(USE_UDEV)
479 return linux_udev_start_event_monitor();
481 return linux_netlink_start_event_monitor();
485 static int linux_stop_event_monitor(void)
487 #if defined(USE_UDEV)
488 return linux_udev_stop_event_monitor();
490 return linux_netlink_stop_event_monitor();
494 static int linux_scan_devices(struct libusb_context *ctx)
498 usbi_mutex_static_lock(&linux_hotplug_lock);
500 #if defined(USE_UDEV)
501 ret = linux_udev_scan_devices(ctx);
503 ret = linux_default_scan_devices(ctx);
506 usbi_mutex_static_unlock(&linux_hotplug_lock);
511 static void op_hotplug_poll(void)
513 #if defined(USE_UDEV)
514 linux_udev_hotplug_poll();
516 linux_netlink_hotplug_poll();
520 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
522 struct linux_device_priv *priv = _device_priv(dev);
523 char filename[PATH_MAX];
526 snprintf(filename, PATH_MAX, "%s/%s/%s",
527 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
528 fd = open(filename, O_RDONLY);
530 usbi_err(DEVICE_CTX(dev),
531 "open %s failed ret=%d errno=%d", filename, fd, errno);
532 return LIBUSB_ERROR_IO;
538 /* Note only suitable for attributes which always read >= 0, < 0 is error */
539 static int __read_sysfs_attr(struct libusb_context *ctx,
540 const char *devname, const char *attr)
542 char filename[PATH_MAX];
546 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
548 f = fopen(filename, "r");
550 if (errno == ENOENT) {
551 /* File doesn't exist. Assume the device has been
552 disconnected (see trac ticket #70). */
553 return LIBUSB_ERROR_NO_DEVICE;
555 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
556 return LIBUSB_ERROR_IO;
559 r = fscanf(f, "%d", &value);
562 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
563 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
566 usbi_err(ctx, "%s contains a negative value", filename);
567 return LIBUSB_ERROR_IO;
573 static int op_get_device_descriptor(struct libusb_device *dev,
574 unsigned char *buffer, int *host_endian)
576 struct linux_device_priv *priv = _device_priv(dev);
578 *host_endian = sysfs_has_descriptors ? 0 : 1;
579 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
584 /* read the bConfigurationValue for a device */
585 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
588 char tmp[5] = {0, 0, 0, 0, 0};
593 fd = _open_sysfs_attr(dev, "bConfigurationValue");
597 r = read(fd, tmp, sizeof(tmp));
600 usbi_err(DEVICE_CTX(dev),
601 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
602 return LIBUSB_ERROR_IO;
604 usbi_dbg("device unconfigured");
609 if (tmp[sizeof(tmp) - 1] != 0) {
610 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
611 return LIBUSB_ERROR_IO;
612 } else if (tmp[0] == 0) {
613 usbi_err(DEVICE_CTX(dev), "no configuration value?");
614 return LIBUSB_ERROR_IO;
617 num = strtol(tmp, &endptr, 10);
619 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
620 return LIBUSB_ERROR_IO;
627 int linux_get_device_address (struct libusb_context *ctx, int detached,
628 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
629 const char *sys_name)
633 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
634 /* can't use sysfs to read the bus and device number if the
635 * device has been detached */
636 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
637 if (NULL == dev_node) {
638 return LIBUSB_ERROR_OTHER;
641 /* will this work with all supported kernel versions? */
642 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
643 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
644 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
645 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
648 return LIBUSB_SUCCESS;
651 usbi_dbg("scan %s", sys_name);
653 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
656 if (sysfs_attr > 255)
657 return LIBUSB_ERROR_INVALID_PARAM;
658 *busnum = (uint8_t) sysfs_attr;
660 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
663 if (sysfs_attr > 255)
664 return LIBUSB_ERROR_INVALID_PARAM;
666 *devaddr = (uint8_t) sysfs_attr;
668 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
670 return LIBUSB_SUCCESS;
673 /* Return offset of the next descriptor with the given type */
674 static int seek_to_next_descriptor(struct libusb_context *ctx,
675 uint8_t descriptor_type, unsigned char *buffer, int size)
677 struct usb_descriptor_header header;
680 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
682 return LIBUSB_ERROR_NOT_FOUND;
685 usbi_err(ctx, "short descriptor read %d/2", size);
686 return LIBUSB_ERROR_IO;
688 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
690 if (i && header.bDescriptorType == descriptor_type)
693 usbi_err(ctx, "bLength overflow by %d bytes", -size);
694 return LIBUSB_ERROR_IO;
697 /* Return offset to next config */
698 static int seek_to_next_config(struct libusb_context *ctx,
699 unsigned char *buffer, int size)
701 struct libusb_config_descriptor config;
704 return LIBUSB_ERROR_NOT_FOUND;
706 if (size < LIBUSB_DT_CONFIG_SIZE) {
707 usbi_err(ctx, "short descriptor read %d/%d",
708 size, LIBUSB_DT_CONFIG_SIZE);
709 return LIBUSB_ERROR_IO;
712 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
713 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
714 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
715 config.bDescriptorType);
716 return LIBUSB_ERROR_IO;
720 * In usbfs the config descriptors are config.wTotalLength bytes apart,
721 * with any short reads from the device appearing as holes in the file.
723 * In sysfs wTotalLength is ignored, instead the kernel returns a
724 * config descriptor with verified bLength fields, with descriptors
725 * with an invalid bLength removed.
727 if (sysfs_has_descriptors) {
728 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
730 if (next == LIBUSB_ERROR_NOT_FOUND)
735 if (next != config.wTotalLength)
736 usbi_warn(ctx, "config length mismatch wTotalLength "
737 "%d real %d", config.wTotalLength, next);
740 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
741 usbi_err(ctx, "invalid wTotalLength %d",
742 config.wTotalLength);
743 return LIBUSB_ERROR_IO;
744 } else if (config.wTotalLength > size) {
745 usbi_warn(ctx, "short descriptor read %d/%d",
746 size, config.wTotalLength);
749 return config.wTotalLength;
753 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
754 uint8_t value, unsigned char **buffer, int *host_endian)
756 struct libusb_context *ctx = DEVICE_CTX(dev);
757 struct linux_device_priv *priv = _device_priv(dev);
758 unsigned char *descriptors = priv->descriptors;
759 int size = priv->descriptors_len;
760 struct libusb_config_descriptor *config;
763 /* Unlike the device desc. config descs. are always in raw format */
766 /* Skip device header */
767 descriptors += DEVICE_DESC_LENGTH;
768 size -= DEVICE_DESC_LENGTH;
770 /* Seek till the config is found, or till "EOF" */
772 int next = seek_to_next_config(ctx, descriptors, size);
775 config = (struct libusb_config_descriptor *)descriptors;
776 if (config->bConfigurationValue == value) {
777 *buffer = descriptors;
785 static int op_get_active_config_descriptor(struct libusb_device *dev,
786 unsigned char *buffer, size_t len, int *host_endian)
789 unsigned char *config_desc;
791 if (sysfs_can_relate_devices) {
792 r = sysfs_get_active_config(dev, &config);
796 /* Use cached bConfigurationValue */
797 struct linux_device_priv *priv = _device_priv(dev);
798 config = priv->active_config;
801 return LIBUSB_ERROR_NOT_FOUND;
803 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
809 memcpy(buffer, config_desc, len);
813 static int op_get_config_descriptor(struct libusb_device *dev,
814 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
816 struct linux_device_priv *priv = _device_priv(dev);
817 unsigned char *descriptors = priv->descriptors;
818 int i, r, size = priv->descriptors_len;
820 /* Unlike the device desc. config descs. are always in raw format */
823 /* Skip device header */
824 descriptors += DEVICE_DESC_LENGTH;
825 size -= DEVICE_DESC_LENGTH;
827 /* Seek till the config is found, or till "EOF" */
829 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
832 if (i == config_index)
839 memcpy(buffer, descriptors, len);
843 /* send a control message to retrieve active configuration */
844 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
846 unsigned char active_config = 0;
849 struct usbfs_ctrltransfer ctrl = {
850 .bmRequestType = LIBUSB_ENDPOINT_IN,
851 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
856 .data = &active_config
859 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
862 return LIBUSB_ERROR_NO_DEVICE;
864 /* we hit this error path frequently with buggy devices :( */
865 usbi_warn(DEVICE_CTX(dev),
866 "get_configuration failed ret=%d errno=%d", r, errno);
867 return LIBUSB_ERROR_IO;
870 return active_config;
873 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
874 uint8_t devaddr, const char *sysfs_dir)
876 struct linux_device_priv *priv = _device_priv(dev);
877 struct libusb_context *ctx = DEVICE_CTX(dev);
878 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
882 dev->bus_number = busnum;
883 dev->device_address = devaddr;
886 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
887 if (!priv->sysfs_dir)
888 return LIBUSB_ERROR_NO_MEM;
889 strcpy(priv->sysfs_dir, sysfs_dir);
891 /* Note speed can contain 1.5, in this case __read_sysfs_attr
892 will stop parsing at the '.' and return 1 */
893 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
896 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
897 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
898 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
899 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
901 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
906 /* cache descriptors in memory */
907 if (sysfs_has_descriptors)
908 fd = _open_sysfs_attr(dev, "descriptors");
910 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
915 descriptors_size *= 2;
916 priv->descriptors = usbi_reallocf(priv->descriptors,
918 if (!priv->descriptors) {
920 return LIBUSB_ERROR_NO_MEM;
922 /* usbfs has holes in the file */
923 if (!sysfs_has_descriptors) {
924 memset(priv->descriptors + priv->descriptors_len,
925 0, descriptors_size - priv->descriptors_len);
927 r = read(fd, priv->descriptors + priv->descriptors_len,
928 descriptors_size - priv->descriptors_len);
930 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
933 return LIBUSB_ERROR_IO;
935 priv->descriptors_len += r;
936 } while (priv->descriptors_len == descriptors_size);
940 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
941 usbi_err(ctx, "short descriptor read (%d)",
942 priv->descriptors_len);
943 return LIBUSB_ERROR_IO;
946 if (sysfs_can_relate_devices)
947 return LIBUSB_SUCCESS;
949 /* cache active config */
950 fd = _get_usbfs_fd(dev, O_RDWR, 1);
952 /* cannot send a control message to determine the active
953 * config. just assume the first one is active. */
954 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
955 "active configuration descriptor");
956 if (priv->descriptors_len >=
957 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
958 struct libusb_config_descriptor config;
959 usbi_parse_descriptor(
960 priv->descriptors + DEVICE_DESC_LENGTH,
961 "bbwbbbbb", &config, 0);
962 priv->active_config = config.bConfigurationValue;
964 priv->active_config = -1; /* No config dt */
966 return LIBUSB_SUCCESS;
969 r = usbfs_get_active_config(dev, fd);
971 priv->active_config = r;
974 /* some buggy devices have a configuration 0, but we're
975 * reaching into the corner of a corner case here, so let's
976 * not support buggy devices in these circumstances.
977 * stick to the specs: a configuration value of 0 means
979 usbi_dbg("active cfg 0? assuming unconfigured device");
980 priv->active_config = -1;
982 } else if (r == LIBUSB_ERROR_IO) {
983 /* buggy devices sometimes fail to report their active config.
984 * assume unconfigured and continue the probing */
985 usbi_warn(ctx, "couldn't query active configuration, assuming"
987 priv->active_config = -1;
989 } /* else r < 0, just return the error code */
995 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
997 struct libusb_context *ctx = DEVICE_CTX(dev);
998 struct libusb_device *it;
999 char *parent_sysfs_dir, *tmp;
1000 int ret, add_parent = 1;
1002 /* XXX -- can we figure out the topology when using usbfs? */
1003 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1004 /* either using usbfs or finding the parent of a root hub */
1005 return LIBUSB_SUCCESS;
1008 parent_sysfs_dir = strdup(sysfs_dir);
1009 if (NULL == parent_sysfs_dir) {
1010 return LIBUSB_ERROR_NO_MEM;
1012 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1013 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1014 dev->port_number = atoi(tmp + 1);
1017 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1019 free (parent_sysfs_dir);
1020 return LIBUSB_SUCCESS;
1023 /* is the parent a root hub? */
1024 if (NULL == strchr(parent_sysfs_dir, '-')) {
1025 tmp = parent_sysfs_dir;
1026 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1029 return LIBUSB_ERROR_NO_MEM;
1034 /* find the parent in the context */
1035 usbi_mutex_lock(&ctx->usb_devs_lock);
1036 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1037 struct linux_device_priv *priv = _device_priv(it);
1038 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1039 dev->parent_dev = libusb_ref_device(it);
1043 usbi_mutex_unlock(&ctx->usb_devs_lock);
1045 if (!dev->parent_dev && add_parent) {
1046 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1048 sysfs_scan_device(ctx, parent_sysfs_dir);
1053 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1054 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1056 free (parent_sysfs_dir);
1058 return LIBUSB_SUCCESS;
1061 int linux_enumerate_device(struct libusb_context *ctx,
1062 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1064 unsigned long session_id;
1065 struct libusb_device *dev;
1068 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1069 * will be reused. instead we should add a simple sysfs attribute with
1071 session_id = busnum << 8 | devaddr;
1072 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1075 dev = usbi_get_device_by_session_id(ctx, session_id);
1077 /* device already exists in the context */
1078 usbi_dbg("session_id %ld already exists", session_id);
1079 libusb_unref_device(dev);
1080 return LIBUSB_SUCCESS;
1083 usbi_dbg("allocating new device for %d/%d (session %ld)",
1084 busnum, devaddr, session_id);
1085 dev = usbi_alloc_device(ctx, session_id);
1087 return LIBUSB_ERROR_NO_MEM;
1089 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1092 r = usbi_sanitize_device(dev);
1096 r = linux_get_parent_info(dev, sysfs_dir);
1101 libusb_unref_device(dev);
1103 usbi_connect_device(dev);
1108 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1110 struct libusb_context *ctx;
1112 usbi_mutex_static_lock(&active_contexts_lock);
1113 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1114 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1116 usbi_mutex_static_unlock(&active_contexts_lock);
1119 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1121 struct libusb_context *ctx;
1122 struct libusb_device *dev;
1123 unsigned long session_id = busnum << 8 | devaddr;
1125 usbi_mutex_static_lock(&active_contexts_lock);
1126 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1127 dev = usbi_get_device_by_session_id (ctx, session_id);
1129 usbi_disconnect_device (dev);
1130 libusb_unref_device(dev);
1132 usbi_dbg("device not found for session %x", session_id);
1135 usbi_mutex_static_unlock(&active_contexts_lock);
1138 #if !defined(USE_UDEV)
1139 /* open a bus directory and adds all discovered devices to the context */
1140 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1143 char dirpath[PATH_MAX];
1144 struct dirent *entry;
1145 int r = LIBUSB_ERROR_IO;
1147 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1148 usbi_dbg("%s", dirpath);
1149 dir = opendir(dirpath);
1151 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1152 /* FIXME: should handle valid race conditions like hub unplugged
1153 * during directory iteration - this is not an error */
1157 while ((entry = readdir(dir))) {
1160 if (entry->d_name[0] == '.')
1163 devaddr = atoi(entry->d_name);
1165 usbi_dbg("unknown dir entry %s", entry->d_name);
1169 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1170 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1181 static int usbfs_get_device_list(struct libusb_context *ctx)
1183 struct dirent *entry;
1184 DIR *buses = opendir(usbfs_path);
1188 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1189 return LIBUSB_ERROR_IO;
1192 while ((entry = readdir(buses))) {
1195 if (entry->d_name[0] == '.')
1200 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1203 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1205 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1209 busnum = atoi(entry->d_name);
1211 usbi_dbg("unknown dir entry %s", entry->d_name);
1215 r = usbfs_scan_busdir(ctx, busnum);
1227 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1229 uint8_t busnum, devaddr;
1232 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1233 if (LIBUSB_SUCCESS != ret) {
1237 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1241 #if !defined(USE_UDEV)
1242 static int sysfs_get_device_list(struct libusb_context *ctx)
1244 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1245 struct dirent *entry;
1246 int r = LIBUSB_ERROR_IO;
1249 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1253 while ((entry = readdir(devices))) {
1254 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1255 || strchr(entry->d_name, ':'))
1258 if (sysfs_scan_device(ctx, entry->d_name)) {
1259 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1270 static int linux_default_scan_devices (struct libusb_context *ctx)
1272 /* we can retrieve device list and descriptors from sysfs or usbfs.
1273 * sysfs is preferable, because if we use usbfs we end up resuming
1274 * any autosuspended USB devices. however, sysfs is not available
1275 * everywhere, so we need a usbfs fallback too.
1277 * as described in the "sysfs vs usbfs" comment at the top of this
1278 * file, sometimes we have sysfs but not enough information to
1279 * relate sysfs devices to usbfs nodes. op_init() determines the
1280 * adequacy of sysfs and sets sysfs_can_relate_devices.
1282 if (sysfs_can_relate_devices != 0)
1283 return sysfs_get_device_list(ctx);
1285 return usbfs_get_device_list(ctx);
1289 static int op_open(struct libusb_device_handle *handle)
1291 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1294 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1295 if (hpriv->fd < 0) {
1296 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1297 /* device will still be marked as attached if hotplug monitor thread
1298 * hasn't processed remove event yet */
1299 usbi_mutex_static_lock(&linux_hotplug_lock);
1300 if (handle->dev->attached) {
1301 usbi_dbg("open failed with no device, but device still attached");
1302 linux_device_disconnected(handle->dev->bus_number,
1303 handle->dev->device_address, NULL);
1305 usbi_mutex_static_unlock(&linux_hotplug_lock);
1310 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1312 if (errno == ENOTTY)
1313 usbi_dbg("getcap not available");
1315 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1317 if (supports_flag_zero_packet)
1318 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1319 if (supports_flag_bulk_continuation)
1320 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1323 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1330 static void op_close(struct libusb_device_handle *dev_handle)
1332 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1333 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1334 if (!hpriv->fd_removed)
1335 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1339 static int op_get_configuration(struct libusb_device_handle *handle,
1344 if (sysfs_can_relate_devices) {
1345 r = sysfs_get_active_config(handle->dev, config);
1347 r = usbfs_get_active_config(handle->dev,
1348 _device_handle_priv(handle)->fd);
1353 if (*config == -1) {
1354 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1361 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1363 struct linux_device_priv *priv = _device_priv(handle->dev);
1364 int fd = _device_handle_priv(handle)->fd;
1365 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1367 if (errno == EINVAL)
1368 return LIBUSB_ERROR_NOT_FOUND;
1369 else if (errno == EBUSY)
1370 return LIBUSB_ERROR_BUSY;
1371 else if (errno == ENODEV)
1372 return LIBUSB_ERROR_NO_DEVICE;
1374 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1375 return LIBUSB_ERROR_OTHER;
1378 /* update our cached active config descriptor */
1379 priv->active_config = config;
1381 return LIBUSB_SUCCESS;
1384 static int claim_interface(struct libusb_device_handle *handle, int iface)
1386 int fd = _device_handle_priv(handle)->fd;
1387 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1389 if (errno == ENOENT)
1390 return LIBUSB_ERROR_NOT_FOUND;
1391 else if (errno == EBUSY)
1392 return LIBUSB_ERROR_BUSY;
1393 else if (errno == ENODEV)
1394 return LIBUSB_ERROR_NO_DEVICE;
1396 usbi_err(HANDLE_CTX(handle),
1397 "claim interface failed, error %d errno %d", r, errno);
1398 return LIBUSB_ERROR_OTHER;
1403 static int release_interface(struct libusb_device_handle *handle, int iface)
1405 int fd = _device_handle_priv(handle)->fd;
1406 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1408 if (errno == ENODEV)
1409 return LIBUSB_ERROR_NO_DEVICE;
1411 usbi_err(HANDLE_CTX(handle),
1412 "release interface failed, error %d errno %d", r, errno);
1413 return LIBUSB_ERROR_OTHER;
1418 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1421 int fd = _device_handle_priv(handle)->fd;
1422 struct usbfs_setinterface setintf;
1425 setintf.interface = iface;
1426 setintf.altsetting = altsetting;
1427 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1429 if (errno == EINVAL)
1430 return LIBUSB_ERROR_NOT_FOUND;
1431 else if (errno == ENODEV)
1432 return LIBUSB_ERROR_NO_DEVICE;
1434 usbi_err(HANDLE_CTX(handle),
1435 "setintf failed error %d errno %d", r, errno);
1436 return LIBUSB_ERROR_OTHER;
1442 static int op_clear_halt(struct libusb_device_handle *handle,
1443 unsigned char endpoint)
1445 int fd = _device_handle_priv(handle)->fd;
1446 unsigned int _endpoint = endpoint;
1447 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1449 if (errno == ENOENT)
1450 return LIBUSB_ERROR_NOT_FOUND;
1451 else if (errno == ENODEV)
1452 return LIBUSB_ERROR_NO_DEVICE;
1454 usbi_err(HANDLE_CTX(handle),
1455 "clear_halt failed error %d errno %d", r, errno);
1456 return LIBUSB_ERROR_OTHER;
1462 static int op_reset_device(struct libusb_device_handle *handle)
1464 int fd = _device_handle_priv(handle)->fd;
1467 /* Doing a device reset will cause the usbfs driver to get unbound
1468 from any interfaces it is bound to. By voluntarily unbinding
1469 the usbfs driver ourself, we stop the kernel from rebinding
1470 the interface after reset (which would end up with the interface
1471 getting bound to the in kernel driver if any). */
1472 for (i = 0; i < USB_MAXINTERFACES; i++) {
1473 if (handle->claimed_interfaces & (1L << i)) {
1474 release_interface(handle, i);
1478 usbi_mutex_lock(&handle->lock);
1479 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1481 if (errno == ENODEV) {
1482 ret = LIBUSB_ERROR_NOT_FOUND;
1486 usbi_err(HANDLE_CTX(handle),
1487 "reset failed error %d errno %d", r, errno);
1488 ret = LIBUSB_ERROR_OTHER;
1492 /* And re-claim any interfaces which were claimed before the reset */
1493 for (i = 0; i < USB_MAXINTERFACES; i++) {
1494 if (handle->claimed_interfaces & (1L << i)) {
1496 * A driver may have completed modprobing during
1497 * IOCTL_USBFS_RESET, and bound itself as soon as
1498 * IOCTL_USBFS_RESET released the device lock
1500 r = detach_kernel_driver_and_claim(handle, i);
1502 usbi_warn(HANDLE_CTX(handle),
1503 "failed to re-claim interface %d after reset: %s",
1504 i, libusb_error_name(r));
1505 handle->claimed_interfaces &= ~(1L << i);
1506 ret = LIBUSB_ERROR_NOT_FOUND;
1511 usbi_mutex_unlock(&handle->lock);
1515 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1516 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1518 int r, fd = _device_handle_priv(handle)->fd;
1519 struct usbfs_streams *streams;
1521 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1522 return LIBUSB_ERROR_INVALID_PARAM;
1524 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1526 return LIBUSB_ERROR_NO_MEM;
1528 streams->num_streams = num_streams;
1529 streams->num_eps = num_endpoints;
1530 memcpy(streams->eps, endpoints, num_endpoints);
1532 r = ioctl(fd, req, streams);
1537 if (errno == ENOTTY)
1538 return LIBUSB_ERROR_NOT_SUPPORTED;
1539 else if (errno == EINVAL)
1540 return LIBUSB_ERROR_INVALID_PARAM;
1541 else if (errno == ENODEV)
1542 return LIBUSB_ERROR_NO_DEVICE;
1544 usbi_err(HANDLE_CTX(handle),
1545 "streams-ioctl failed error %d errno %d", r, errno);
1546 return LIBUSB_ERROR_OTHER;
1551 static int op_alloc_streams(struct libusb_device_handle *handle,
1552 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1554 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1555 num_streams, endpoints, num_endpoints);
1558 static int op_free_streams(struct libusb_device_handle *handle,
1559 unsigned char *endpoints, int num_endpoints)
1561 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1562 endpoints, num_endpoints);
1565 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1568 int fd = _device_handle_priv(handle)->fd;
1569 struct usbfs_getdriver getdrv;
1572 getdrv.interface = interface;
1573 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1575 if (errno == ENODATA)
1577 else if (errno == ENODEV)
1578 return LIBUSB_ERROR_NO_DEVICE;
1580 usbi_err(HANDLE_CTX(handle),
1581 "get driver failed error %d errno %d", r, errno);
1582 return LIBUSB_ERROR_OTHER;
1585 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1588 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1591 int fd = _device_handle_priv(handle)->fd;
1592 struct usbfs_ioctl command;
1593 struct usbfs_getdriver getdrv;
1596 command.ifno = interface;
1597 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1598 command.data = NULL;
1600 getdrv.interface = interface;
1601 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1602 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1603 return LIBUSB_ERROR_NOT_FOUND;
1605 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1607 if (errno == ENODATA)
1608 return LIBUSB_ERROR_NOT_FOUND;
1609 else if (errno == EINVAL)
1610 return LIBUSB_ERROR_INVALID_PARAM;
1611 else if (errno == ENODEV)
1612 return LIBUSB_ERROR_NO_DEVICE;
1614 usbi_err(HANDLE_CTX(handle),
1615 "detach failed error %d errno %d", r, errno);
1616 return LIBUSB_ERROR_OTHER;
1622 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1625 int fd = _device_handle_priv(handle)->fd;
1626 struct usbfs_ioctl command;
1629 command.ifno = interface;
1630 command.ioctl_code = IOCTL_USBFS_CONNECT;
1631 command.data = NULL;
1633 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1635 if (errno == ENODATA)
1636 return LIBUSB_ERROR_NOT_FOUND;
1637 else if (errno == EINVAL)
1638 return LIBUSB_ERROR_INVALID_PARAM;
1639 else if (errno == ENODEV)
1640 return LIBUSB_ERROR_NO_DEVICE;
1641 else if (errno == EBUSY)
1642 return LIBUSB_ERROR_BUSY;
1644 usbi_err(HANDLE_CTX(handle),
1645 "attach failed error %d errno %d", r, errno);
1646 return LIBUSB_ERROR_OTHER;
1647 } else if (r == 0) {
1648 return LIBUSB_ERROR_NOT_FOUND;
1654 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1657 struct usbfs_disconnect_claim dc;
1658 int r, fd = _device_handle_priv(handle)->fd;
1660 dc.interface = interface;
1661 strcpy(dc.driver, "usbfs");
1662 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1663 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1664 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1670 return LIBUSB_ERROR_BUSY;
1672 return LIBUSB_ERROR_INVALID_PARAM;
1674 return LIBUSB_ERROR_NO_DEVICE;
1676 usbi_err(HANDLE_CTX(handle),
1677 "disconnect-and-claim failed errno %d", errno);
1678 return LIBUSB_ERROR_OTHER;
1681 /* Fallback code for kernels which don't support the
1682 disconnect-and-claim ioctl */
1683 r = op_detach_kernel_driver(handle, interface);
1684 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1687 return claim_interface(handle, interface);
1690 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1692 if (handle->auto_detach_kernel_driver)
1693 return detach_kernel_driver_and_claim(handle, iface);
1695 return claim_interface(handle, iface);
1698 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1702 r = release_interface(handle, iface);
1706 if (handle->auto_detach_kernel_driver)
1707 op_attach_kernel_driver(handle, iface);
1712 static void op_destroy_device(struct libusb_device *dev)
1714 struct linux_device_priv *priv = _device_priv(dev);
1715 if (priv->descriptors)
1716 free(priv->descriptors);
1717 if (priv->sysfs_dir)
1718 free(priv->sysfs_dir);
1721 /* URBs are discarded in reverse order of submission to avoid races. */
1722 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1724 struct libusb_transfer *transfer =
1725 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1726 struct linux_transfer_priv *tpriv =
1727 usbi_transfer_get_os_priv(itransfer);
1728 struct linux_device_handle_priv *dpriv =
1729 _device_handle_priv(transfer->dev_handle);
1731 struct usbfs_urb *urb;
1733 for (i = last_plus_one - 1; i >= first; i--) {
1734 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1735 urb = tpriv->iso_urbs[i];
1737 urb = &tpriv->urbs[i];
1739 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1742 if (EINVAL == errno) {
1743 usbi_dbg("URB not found --> assuming ready to be reaped");
1744 if (i == (last_plus_one - 1))
1745 ret = LIBUSB_ERROR_NOT_FOUND;
1746 } else if (ENODEV == errno) {
1747 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1748 ret = LIBUSB_ERROR_NO_DEVICE;
1750 usbi_warn(TRANSFER_CTX(transfer),
1751 "unrecognised discard errno %d", errno);
1752 ret = LIBUSB_ERROR_OTHER;
1758 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1761 for (i = 0; i < tpriv->num_urbs; i++) {
1762 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1768 free(tpriv->iso_urbs);
1769 tpriv->iso_urbs = NULL;
1772 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1774 struct libusb_transfer *transfer =
1775 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1776 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1777 struct linux_device_handle_priv *dpriv =
1778 _device_handle_priv(transfer->dev_handle);
1779 struct usbfs_urb *urbs;
1780 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1781 == LIBUSB_ENDPOINT_OUT;
1782 int bulk_buffer_len, use_bulk_continuation;
1786 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1787 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1788 return LIBUSB_ERROR_NOT_SUPPORTED;
1791 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1792 * around this by splitting large transfers into 16k blocks, and then
1793 * submit all urbs at once. it would be simpler to submit one urb at
1794 * a time, but there is a big performance gain doing it this way.
1796 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1797 * using arbritary large transfers can still be a bad idea though, as
1798 * the kernel needs to allocate physical contiguous memory for this,
1799 * which may fail for large buffers.
1801 * The kernel solves this problem by splitting the transfer into
1802 * blocks itself when the host-controller is scatter-gather capable
1803 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1805 * Last, there is the issue of short-transfers when splitting, for
1806 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1807 * is needed, but this is not always available.
1809 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1810 /* Good! Just submit everything in one go */
1811 bulk_buffer_len = transfer->length ? transfer->length : 1;
1812 use_bulk_continuation = 0;
1813 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1814 /* Split the transfers and use bulk-continuation to
1815 avoid issues with short-transfers */
1816 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1817 use_bulk_continuation = 1;
1818 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1819 /* Don't split, assume the kernel can alloc the buffer
1820 (otherwise the submit will fail with -ENOMEM) */
1821 bulk_buffer_len = transfer->length ? transfer->length : 1;
1822 use_bulk_continuation = 0;
1824 /* Bad, splitting without bulk-continuation, short transfers
1825 which end before the last urb will not work reliable! */
1826 /* Note we don't warn here as this is "normal" on kernels <
1827 2.6.32 and not a problem for most applications */
1828 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1829 use_bulk_continuation = 0;
1832 int num_urbs = transfer->length / bulk_buffer_len;
1833 int last_urb_partial = 0;
1835 if (transfer->length == 0) {
1837 } else if ((transfer->length % bulk_buffer_len) > 0) {
1838 last_urb_partial = 1;
1841 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1843 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1845 return LIBUSB_ERROR_NO_MEM;
1847 tpriv->num_urbs = num_urbs;
1848 tpriv->num_retired = 0;
1849 tpriv->reap_action = NORMAL;
1850 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1852 for (i = 0; i < num_urbs; i++) {
1853 struct usbfs_urb *urb = &urbs[i];
1854 urb->usercontext = itransfer;
1855 switch (transfer->type) {
1856 case LIBUSB_TRANSFER_TYPE_BULK:
1857 urb->type = USBFS_URB_TYPE_BULK;
1860 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1861 urb->type = USBFS_URB_TYPE_BULK;
1862 urb->stream_id = itransfer->stream_id;
1864 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1865 urb->type = USBFS_URB_TYPE_INTERRUPT;
1868 urb->endpoint = transfer->endpoint;
1869 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1870 /* don't set the short not ok flag for the last URB */
1871 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1872 urb->flags = USBFS_URB_SHORT_NOT_OK;
1873 if (i == num_urbs - 1 && last_urb_partial)
1874 urb->buffer_length = transfer->length % bulk_buffer_len;
1875 else if (transfer->length == 0)
1876 urb->buffer_length = 0;
1878 urb->buffer_length = bulk_buffer_len;
1880 if (i > 0 && use_bulk_continuation)
1881 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1883 /* we have already checked that the flag is supported */
1884 if (is_out && i == num_urbs - 1 &&
1885 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1886 urb->flags |= USBFS_URB_ZERO_PACKET;
1888 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1890 if (errno == ENODEV) {
1891 r = LIBUSB_ERROR_NO_DEVICE;
1893 usbi_err(TRANSFER_CTX(transfer),
1894 "submiturb failed error %d errno=%d", r, errno);
1895 r = LIBUSB_ERROR_IO;
1898 /* if the first URB submission fails, we can simply free up and
1899 * return failure immediately. */
1901 usbi_dbg("first URB failed, easy peasy");
1907 /* if it's not the first URB that failed, the situation is a bit
1908 * tricky. we may need to discard all previous URBs. there are
1910 * - discarding is asynchronous - discarded urbs will be reaped
1911 * later. the user must not have freed the transfer when the
1912 * discarded URBs are reaped, otherwise libusb will be using
1914 * - the earlier URBs may have completed successfully and we do
1915 * not want to throw away any data.
1916 * - this URB failing may be no error; EREMOTEIO means that
1917 * this transfer simply didn't need all the URBs we submitted
1918 * so, we report that the transfer was submitted successfully and
1919 * in case of error we discard all previous URBs. later when
1920 * the final reap completes we can report error to the user,
1921 * or success if an earlier URB was completed successfully.
1923 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1925 /* The URBs we haven't submitted yet we count as already
1927 tpriv->num_retired += num_urbs - i;
1929 /* If we completed short then don't try to discard. */
1930 if (COMPLETED_EARLY == tpriv->reap_action)
1933 discard_urbs(itransfer, 0, i);
1935 usbi_dbg("reporting successful submission but waiting for %d "
1936 "discards before reporting error", i);
1944 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1946 struct libusb_transfer *transfer =
1947 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1948 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1949 struct linux_device_handle_priv *dpriv =
1950 _device_handle_priv(transfer->dev_handle);
1951 struct usbfs_urb **urbs;
1953 int num_packets = transfer->num_iso_packets;
1955 int this_urb_len = 0;
1957 int packet_offset = 0;
1958 unsigned int packet_len;
1959 unsigned char *urb_buffer = transfer->buffer;
1961 /* usbfs places arbitrary limits on iso URBs. this limit has changed
1962 * at least three times, and it's difficult to accurately detect which
1963 * limit this running kernel might impose. so we attempt to submit
1964 * whatever the user has provided. if the kernel rejects the request
1965 * due to its size, we return an error indicating such to the user.
1968 /* calculate how many URBs we need */
1969 for (i = 0; i < num_packets; i++) {
1970 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1971 packet_len = transfer->iso_packet_desc[i].length;
1973 if (packet_len > space_remaining) {
1975 this_urb_len = packet_len;
1976 /* check that we can actually support this packet length */
1977 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
1978 return LIBUSB_ERROR_INVALID_PARAM;
1980 this_urb_len += packet_len;
1983 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
1985 urbs = calloc(num_urbs, sizeof(*urbs));
1987 return LIBUSB_ERROR_NO_MEM;
1989 tpriv->iso_urbs = urbs;
1990 tpriv->num_urbs = num_urbs;
1991 tpriv->num_retired = 0;
1992 tpriv->reap_action = NORMAL;
1993 tpriv->iso_packet_offset = 0;
1995 /* allocate + initialize each URB with the correct number of packets */
1996 for (i = 0; i < num_urbs; i++) {
1997 struct usbfs_urb *urb;
1998 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1999 int urb_packet_offset = 0;
2000 unsigned char *urb_buffer_orig = urb_buffer;
2004 /* swallow up all the packets we can fit into this URB */
2005 while (packet_offset < transfer->num_iso_packets) {
2006 packet_len = transfer->iso_packet_desc[packet_offset].length;
2007 if (packet_len <= space_remaining_in_urb) {
2009 urb_packet_offset++;
2011 space_remaining_in_urb -= packet_len;
2012 urb_buffer += packet_len;
2014 /* it can't fit, save it for the next URB */
2019 alloc_size = sizeof(*urb)
2020 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2021 urb = calloc(1, alloc_size);
2023 free_iso_urbs(tpriv);
2024 return LIBUSB_ERROR_NO_MEM;
2028 /* populate packet lengths */
2029 for (j = 0, k = packet_offset - urb_packet_offset;
2030 k < packet_offset; k++, j++) {
2031 packet_len = transfer->iso_packet_desc[k].length;
2032 urb->iso_frame_desc[j].length = packet_len;
2035 urb->usercontext = itransfer;
2036 urb->type = USBFS_URB_TYPE_ISO;
2037 /* FIXME: interface for non-ASAP data? */
2038 urb->flags = USBFS_URB_ISO_ASAP;
2039 urb->endpoint = transfer->endpoint;
2040 urb->number_of_packets = urb_packet_offset;
2041 urb->buffer = urb_buffer_orig;
2045 for (i = 0; i < num_urbs; i++) {
2046 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2048 if (errno == ENODEV) {
2049 r = LIBUSB_ERROR_NO_DEVICE;
2050 } else if (errno == EINVAL) {
2051 usbi_warn(TRANSFER_CTX(transfer),
2052 "submiturb failed, transfer too large");
2053 r = LIBUSB_ERROR_INVALID_PARAM;
2055 usbi_err(TRANSFER_CTX(transfer),
2056 "submiturb failed error %d errno=%d", r, errno);
2057 r = LIBUSB_ERROR_IO;
2060 /* if the first URB submission fails, we can simply free up and
2061 * return failure immediately. */
2063 usbi_dbg("first URB failed, easy peasy");
2064 free_iso_urbs(tpriv);
2068 /* if it's not the first URB that failed, the situation is a bit
2069 * tricky. we must discard all previous URBs. there are
2071 * - discarding is asynchronous - discarded urbs will be reaped
2072 * later. the user must not have freed the transfer when the
2073 * discarded URBs are reaped, otherwise libusb will be using
2075 * - the earlier URBs may have completed successfully and we do
2076 * not want to throw away any data.
2077 * so, in this case we discard all the previous URBs BUT we report
2078 * that the transfer was submitted successfully. then later when
2079 * the final discard completes we can report error to the user.
2081 tpriv->reap_action = SUBMIT_FAILED;
2083 /* The URBs we haven't submitted yet we count as already
2085 tpriv->num_retired = num_urbs - i;
2086 discard_urbs(itransfer, 0, i);
2088 usbi_dbg("reporting successful submission but waiting for %d "
2089 "discards before reporting error", i);
2097 static int submit_control_transfer(struct usbi_transfer *itransfer)
2099 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2100 struct libusb_transfer *transfer =
2101 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2102 struct linux_device_handle_priv *dpriv =
2103 _device_handle_priv(transfer->dev_handle);
2104 struct usbfs_urb *urb;
2107 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2108 return LIBUSB_ERROR_INVALID_PARAM;
2110 urb = calloc(1, sizeof(struct usbfs_urb));
2112 return LIBUSB_ERROR_NO_MEM;
2114 tpriv->num_urbs = 1;
2115 tpriv->reap_action = NORMAL;
2117 urb->usercontext = itransfer;
2118 urb->type = USBFS_URB_TYPE_CONTROL;
2119 urb->endpoint = transfer->endpoint;
2120 urb->buffer = transfer->buffer;
2121 urb->buffer_length = transfer->length;
2123 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2127 if (errno == ENODEV)
2128 return LIBUSB_ERROR_NO_DEVICE;
2130 usbi_err(TRANSFER_CTX(transfer),
2131 "submiturb failed error %d errno=%d", r, errno);
2132 return LIBUSB_ERROR_IO;
2137 static int op_submit_transfer(struct usbi_transfer *itransfer)
2139 struct libusb_transfer *transfer =
2140 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2142 switch (transfer->type) {
2143 case LIBUSB_TRANSFER_TYPE_CONTROL:
2144 return submit_control_transfer(itransfer);
2145 case LIBUSB_TRANSFER_TYPE_BULK:
2146 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2147 return submit_bulk_transfer(itransfer);
2148 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2149 return submit_bulk_transfer(itransfer);
2150 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2151 return submit_iso_transfer(itransfer);
2153 usbi_err(TRANSFER_CTX(transfer),
2154 "unknown endpoint type %d", transfer->type);
2155 return LIBUSB_ERROR_INVALID_PARAM;
2159 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2161 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2162 struct libusb_transfer *transfer =
2163 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2167 return LIBUSB_ERROR_NOT_FOUND;
2169 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2173 switch (transfer->type) {
2174 case LIBUSB_TRANSFER_TYPE_BULK:
2175 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2176 if (tpriv->reap_action == ERROR)
2178 /* else, fall through */
2180 tpriv->reap_action = CANCELLED;
2186 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2188 struct libusb_transfer *transfer =
2189 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2190 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2192 /* urbs can be freed also in submit_transfer so lock mutex first */
2193 switch (transfer->type) {
2194 case LIBUSB_TRANSFER_TYPE_CONTROL:
2195 case LIBUSB_TRANSFER_TYPE_BULK:
2196 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2197 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2203 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2204 if (tpriv->iso_urbs) {
2205 free_iso_urbs(tpriv);
2206 tpriv->iso_urbs = NULL;
2210 usbi_err(TRANSFER_CTX(transfer),
2211 "unknown endpoint type %d", transfer->type);
2215 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2216 struct usbfs_urb *urb)
2218 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2219 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2220 int urb_idx = urb - tpriv->urbs;
2222 usbi_mutex_lock(&itransfer->lock);
2223 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2224 urb_idx + 1, tpriv->num_urbs);
2226 tpriv->num_retired++;
2228 if (tpriv->reap_action != NORMAL) {
2229 /* cancelled, submit_fail, or completed early */
2230 usbi_dbg("abnormal reap: urb status %d", urb->status);
2232 /* even though we're in the process of cancelling, it's possible that
2233 * we may receive some data in these URBs that we don't want to lose.
2235 * 1. while the kernel is cancelling all the packets that make up an
2236 * URB, a few of them might complete. so we get back a successful
2237 * cancellation *and* some data.
2238 * 2. we receive a short URB which marks the early completion condition,
2239 * so we start cancelling the remaining URBs. however, we're too
2240 * slow and another URB completes (or at least completes partially).
2241 * (this can't happen since we always use BULK_CONTINUATION.)
2243 * When this happens, our objectives are not to lose any "surplus" data,
2244 * and also to stick it at the end of the previously-received data
2245 * (closing any holes), so that libusb reports the total amount of
2246 * transferred data and presents it in a contiguous chunk.
2248 if (urb->actual_length > 0) {
2249 unsigned char *target = transfer->buffer + itransfer->transferred;
2250 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2251 if (urb->buffer != target) {
2252 usbi_dbg("moving surplus data from offset %d to offset %d",
2253 (unsigned char *) urb->buffer - transfer->buffer,
2254 target - transfer->buffer);
2255 memmove(target, urb->buffer, urb->actual_length);
2257 itransfer->transferred += urb->actual_length;
2260 if (tpriv->num_retired == tpriv->num_urbs) {
2261 usbi_dbg("abnormal reap: last URB handled, reporting");
2262 if (tpriv->reap_action != COMPLETED_EARLY &&
2263 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2264 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2270 itransfer->transferred += urb->actual_length;
2272 /* Many of these errors can occur on *any* urb of a multi-urb
2273 * transfer. When they do, we tear down the rest of the transfer.
2275 switch (urb->status) {
2278 case -EREMOTEIO: /* short transfer */
2280 case -ENOENT: /* cancelled */
2285 usbi_dbg("device removed");
2286 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2287 goto cancel_remaining;
2289 usbi_dbg("detected endpoint stall");
2290 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2291 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2292 goto cancel_remaining;
2294 /* overflow can only ever occur in the last urb */
2295 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2296 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2297 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2304 usbi_dbg("low level error %d", urb->status);
2305 tpriv->reap_action = ERROR;
2306 goto cancel_remaining;
2308 usbi_warn(ITRANSFER_CTX(itransfer),
2309 "unrecognised urb status %d", urb->status);
2310 tpriv->reap_action = ERROR;
2311 goto cancel_remaining;
2314 /* if we're the last urb or we got less data than requested then we're
2316 if (urb_idx == tpriv->num_urbs - 1) {
2317 usbi_dbg("last URB in transfer --> complete!");
2319 } else if (urb->actual_length < urb->buffer_length) {
2320 usbi_dbg("short transfer %d/%d --> complete!",
2321 urb->actual_length, urb->buffer_length);
2322 if (tpriv->reap_action == NORMAL)
2323 tpriv->reap_action = COMPLETED_EARLY;
2328 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2329 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2331 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2334 /* cancel remaining urbs and wait for their completion before
2335 * reporting results */
2336 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2339 usbi_mutex_unlock(&itransfer->lock);
2345 usbi_mutex_unlock(&itransfer->lock);
2346 return CANCELLED == tpriv->reap_action ?
2347 usbi_handle_transfer_cancellation(itransfer) :
2348 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2351 static int handle_iso_completion(struct usbi_transfer *itransfer,
2352 struct usbfs_urb *urb)
2354 struct libusb_transfer *transfer =
2355 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2356 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2357 int num_urbs = tpriv->num_urbs;
2360 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2362 usbi_mutex_lock(&itransfer->lock);
2363 for (i = 0; i < num_urbs; i++) {
2364 if (urb == tpriv->iso_urbs[i]) {
2370 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2371 usbi_mutex_unlock(&itransfer->lock);
2372 return LIBUSB_ERROR_NOT_FOUND;
2375 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2378 /* copy isochronous results back in */
2380 for (i = 0; i < urb->number_of_packets; i++) {
2381 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2382 struct libusb_iso_packet_descriptor *lib_desc =
2383 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2384 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2385 switch (urb_desc->status) {
2388 case -ENOENT: /* cancelled */
2393 usbi_dbg("device removed");
2394 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2397 usbi_dbg("detected endpoint stall");
2398 lib_desc->status = LIBUSB_TRANSFER_STALL;
2401 usbi_dbg("overflow error");
2402 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2410 usbi_dbg("low-level USB error %d", urb_desc->status);
2411 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2414 usbi_warn(TRANSFER_CTX(transfer),
2415 "unrecognised urb status %d", urb_desc->status);
2416 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2419 lib_desc->actual_length = urb_desc->actual_length;
2422 tpriv->num_retired++;
2424 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2425 usbi_dbg("CANCEL: urb status %d", urb->status);
2427 if (tpriv->num_retired == num_urbs) {
2428 usbi_dbg("CANCEL: last URB handled, reporting");
2429 free_iso_urbs(tpriv);
2430 if (tpriv->reap_action == CANCELLED) {
2431 usbi_mutex_unlock(&itransfer->lock);
2432 return usbi_handle_transfer_cancellation(itransfer);
2434 usbi_mutex_unlock(&itransfer->lock);
2435 return usbi_handle_transfer_completion(itransfer,
2436 LIBUSB_TRANSFER_ERROR);
2442 switch (urb->status) {
2445 case -ENOENT: /* cancelled */
2449 usbi_dbg("device removed");
2450 status = LIBUSB_TRANSFER_NO_DEVICE;
2453 usbi_warn(TRANSFER_CTX(transfer),
2454 "unrecognised urb status %d", urb->status);
2455 status = LIBUSB_TRANSFER_ERROR;
2459 /* if we're the last urb then we're done */
2460 if (urb_idx == num_urbs) {
2461 usbi_dbg("last URB in transfer --> complete!");
2462 free_iso_urbs(tpriv);
2463 usbi_mutex_unlock(&itransfer->lock);
2464 return usbi_handle_transfer_completion(itransfer, status);
2468 usbi_mutex_unlock(&itransfer->lock);
2472 static int handle_control_completion(struct usbi_transfer *itransfer,
2473 struct usbfs_urb *urb)
2475 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2478 usbi_mutex_lock(&itransfer->lock);
2479 usbi_dbg("handling completion status %d", urb->status);
2481 itransfer->transferred += urb->actual_length;
2483 if (tpriv->reap_action == CANCELLED) {
2484 if (urb->status != 0 && urb->status != -ENOENT)
2485 usbi_warn(ITRANSFER_CTX(itransfer),
2486 "cancel: unrecognised urb status %d", urb->status);
2489 usbi_mutex_unlock(&itransfer->lock);
2490 return usbi_handle_transfer_cancellation(itransfer);
2493 switch (urb->status) {
2495 status = LIBUSB_TRANSFER_COMPLETED;
2497 case -ENOENT: /* cancelled */
2498 status = LIBUSB_TRANSFER_CANCELLED;
2502 usbi_dbg("device removed");
2503 status = LIBUSB_TRANSFER_NO_DEVICE;
2506 usbi_dbg("unsupported control request");
2507 status = LIBUSB_TRANSFER_STALL;
2510 usbi_dbg("control overflow error");
2511 status = LIBUSB_TRANSFER_OVERFLOW;
2518 usbi_dbg("low-level bus error occurred");
2519 status = LIBUSB_TRANSFER_ERROR;
2522 usbi_warn(ITRANSFER_CTX(itransfer),
2523 "unrecognised urb status %d", urb->status);
2524 status = LIBUSB_TRANSFER_ERROR;
2530 usbi_mutex_unlock(&itransfer->lock);
2531 return usbi_handle_transfer_completion(itransfer, status);
2534 static int reap_for_handle(struct libusb_device_handle *handle)
2536 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2538 struct usbfs_urb *urb;
2539 struct usbi_transfer *itransfer;
2540 struct libusb_transfer *transfer;
2542 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2543 if (r == -1 && errno == EAGAIN)
2546 if (errno == ENODEV)
2547 return LIBUSB_ERROR_NO_DEVICE;
2549 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2551 return LIBUSB_ERROR_IO;
2554 itransfer = urb->usercontext;
2555 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2557 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2558 urb->actual_length);
2560 switch (transfer->type) {
2561 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2562 return handle_iso_completion(itransfer, urb);
2563 case LIBUSB_TRANSFER_TYPE_BULK:
2564 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2565 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2566 return handle_bulk_completion(itransfer, urb);
2567 case LIBUSB_TRANSFER_TYPE_CONTROL:
2568 return handle_control_completion(itransfer, urb);
2570 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2572 return LIBUSB_ERROR_OTHER;
2576 static int op_handle_events(struct libusb_context *ctx,
2577 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2582 usbi_mutex_lock(&ctx->open_devs_lock);
2583 for (i = 0; i < nfds && num_ready > 0; i++) {
2584 struct pollfd *pollfd = &fds[i];
2585 struct libusb_device_handle *handle;
2586 struct linux_device_handle_priv *hpriv = NULL;
2588 if (!pollfd->revents)
2592 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2593 hpriv = _device_handle_priv(handle);
2594 if (hpriv->fd == pollfd->fd)
2598 if (!hpriv || hpriv->fd != pollfd->fd) {
2599 usbi_err(ctx, "cannot find handle for fd %d",
2604 if (pollfd->revents & POLLERR) {
2605 /* remove the fd from the pollfd set so that it doesn't continuously
2606 * trigger an event, and flag that it has been removed so op_close()
2607 * doesn't try to remove it a second time */
2608 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2609 hpriv->fd_removed = 1;
2611 /* device will still be marked as attached if hotplug monitor thread
2612 * hasn't processed remove event yet */
2613 usbi_mutex_static_lock(&linux_hotplug_lock);
2614 if (handle->dev->attached)
2615 linux_device_disconnected(handle->dev->bus_number,
2616 handle->dev->device_address, NULL);
2617 usbi_mutex_static_unlock(&linux_hotplug_lock);
2619 if (!(hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT)) {
2620 usbi_handle_disconnect(handle);
2626 r = reap_for_handle(handle);
2628 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2636 usbi_mutex_unlock(&ctx->open_devs_lock);
2640 static int op_clock_gettime(int clk_id, struct timespec *tp)
2643 case USBI_CLOCK_MONOTONIC:
2644 return clock_gettime(monotonic_clkid, tp);
2645 case USBI_CLOCK_REALTIME:
2646 return clock_gettime(CLOCK_REALTIME, tp);
2648 return LIBUSB_ERROR_INVALID_PARAM;
2652 #ifdef USBI_TIMERFD_AVAILABLE
2653 static clockid_t op_get_timerfd_clockid(void)
2655 return monotonic_clkid;
2660 const struct usbi_os_backend linux_usbfs_backend = {
2661 .name = "Linux usbfs",
2662 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2665 .get_device_list = NULL,
2666 .hotplug_poll = op_hotplug_poll,
2667 .get_device_descriptor = op_get_device_descriptor,
2668 .get_active_config_descriptor = op_get_active_config_descriptor,
2669 .get_config_descriptor = op_get_config_descriptor,
2670 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2674 .get_configuration = op_get_configuration,
2675 .set_configuration = op_set_configuration,
2676 .claim_interface = op_claim_interface,
2677 .release_interface = op_release_interface,
2679 .set_interface_altsetting = op_set_interface,
2680 .clear_halt = op_clear_halt,
2681 .reset_device = op_reset_device,
2683 .alloc_streams = op_alloc_streams,
2684 .free_streams = op_free_streams,
2686 .kernel_driver_active = op_kernel_driver_active,
2687 .detach_kernel_driver = op_detach_kernel_driver,
2688 .attach_kernel_driver = op_attach_kernel_driver,
2690 .destroy_device = op_destroy_device,
2692 .submit_transfer = op_submit_transfer,
2693 .cancel_transfer = op_cancel_transfer,
2694 .clear_transfer_priv = op_clear_transfer_priv,
2696 .handle_events = op_handle_events,
2698 .clock_gettime = op_clock_gettime,
2700 #ifdef USBI_TIMERFD_AVAILABLE
2701 .get_timerfd_clockid = op_get_timerfd_clockid,
2704 .device_priv_size = sizeof(struct linux_device_priv),
2705 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2706 .transfer_priv_size = sizeof(struct linux_transfer_priv),