1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusbx
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>
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 2.6.32 adds support for a bulk continuation URB flag. this basically
85 * allows us to mark URBs as being part of a specific logical transfer when
86 * we submit them to the kernel. then, on any error except a cancellation, all
87 * URBs within that transfer will be cancelled and no more URBs will be
88 * accepted for the transfer, meaning that no more data can creep in.
90 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
91 * (in either direction) except the first.
92 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
93 * last; it means that the kernel should treat a short reply as an error.
94 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
95 * transfers can't be short unless there's already some sort of error), and
96 * setting this flag is disallowed (a kernel with USB debugging enabled will
99 static int supports_flag_bulk_continuation = -1;
101 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
102 * allows us to mark URBs that should be followed by a zero length data
103 * packet, which can be required by device- or class-specific protocols.
105 static int supports_flag_zero_packet = -1;
107 /* clock ID for monotonic clock, as not all clock sources are available on all
108 * systems. appropriate choice made at initialization time. */
109 static clockid_t monotonic_clkid = -1;
111 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
112 * to sysfs, so we can relate devices. This also implies that we can read
113 * the active configuration through bConfigurationValue */
114 static int sysfs_can_relate_devices = -1;
116 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
117 * config descriptors (rather then just the active config) to the sysfs
118 * descriptors file, so from then on we can use them. */
119 static int sysfs_has_descriptors = -1;
121 /* how many times have we initted (and not exited) ? */
122 static volatile int init_count = 0;
124 /* Serialize hotplug start/stop */
125 usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
126 /* Serialize scan-devices, event-thread, and poll */
127 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
129 static int linux_start_event_monitor(void);
130 static int linux_stop_event_monitor(void);
131 static int linux_scan_devices(struct libusb_context *ctx);
132 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
133 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
135 #if !defined(USE_UDEV)
136 static int linux_default_scan_devices (struct libusb_context *ctx);
139 struct linux_device_priv {
141 unsigned char *descriptors;
143 int active_config; /* cache val for !sysfs_can_relate_devices */
146 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);
189 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
190 usbfs_path, dev->bus_number, dev->device_address);
192 snprintf(path, PATH_MAX, "%s/%03d/%03d",
193 usbfs_path, dev->bus_number, dev->device_address);
195 fd = open(path, mode);
197 return fd; /* Success */
200 usbi_err(ctx, "libusbx couldn't open USB device %s: %s",
201 path, strerror(errno));
202 if (errno == EACCES && mode == O_RDWR)
203 usbi_err(ctx, "libusbx requires write access to USB "
208 return LIBUSB_ERROR_ACCESS;
210 return LIBUSB_ERROR_NO_DEVICE;
211 return LIBUSB_ERROR_IO;
214 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
216 return (struct linux_device_priv *) dev->os_priv;
219 static struct linux_device_handle_priv *_device_handle_priv(
220 struct libusb_device_handle *handle)
222 return (struct linux_device_handle_priv *) handle->os_priv;
225 /* check dirent for a /dev/usbdev%d.%d name
226 * optionally return bus/device on success */
227 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
231 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
234 usbi_dbg("found: %s", entry->d_name);
242 static int check_usb_vfs(const char *dirname)
245 struct dirent *entry;
248 dir = opendir(dirname);
252 while ((entry = readdir(dir)) != NULL) {
253 if (entry->d_name[0] == '.')
256 /* We assume if we find any files that it must be the right place */
265 static const char *find_usbfs_path(void)
267 const char *path = "/dev/bus/usb";
268 const char *ret = NULL;
270 if (check_usb_vfs(path)) {
273 path = "/proc/bus/usb";
274 if (check_usb_vfs(path))
278 /* look for /dev/usbdev*.* if the normal places fail */
280 struct dirent *entry;
286 while ((entry = readdir(dir)) != NULL) {
287 if (_is_usbdev_entry(entry, NULL, NULL)) {
288 /* found one; that's enough */
299 usbi_dbg("found usbfs at %s", ret);
304 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
305 * seem to lack it). fall back to REALTIME if we have to. */
306 static clockid_t find_monotonic_clock(void)
308 #ifdef CLOCK_MONOTONIC
312 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
313 * because it's not available through timerfd */
314 r = clock_gettime(CLOCK_MONOTONIC, &ts);
316 return CLOCK_MONOTONIC;
317 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
320 return CLOCK_REALTIME;
323 static int kernel_version_ge(int major, int minor, int sublevel)
326 int atoms, kmajor, kminor, ksublevel;
330 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
339 /* kmajor == major */
341 return 0 == minor && 0 == sublevel;
347 /* kminor == minor */
349 return 0 == sublevel;
351 return ksublevel >= sublevel;
354 static int op_init(struct libusb_context *ctx)
359 usbfs_path = find_usbfs_path();
361 usbi_err(ctx, "could not find usbfs");
362 return LIBUSB_ERROR_OTHER;
365 if (monotonic_clkid == -1)
366 monotonic_clkid = find_monotonic_clock();
368 if (supports_flag_bulk_continuation == -1) {
369 /* bulk continuation URB flag available from Linux 2.6.32 */
370 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
371 if (supports_flag_bulk_continuation == -1) {
372 usbi_err(ctx, "error checking for bulk continuation support");
373 return LIBUSB_ERROR_OTHER;
377 if (supports_flag_bulk_continuation)
378 usbi_dbg("bulk continuation flag supported");
380 if (-1 == supports_flag_zero_packet) {
381 /* zero length packet URB flag fixed since Linux 2.6.31 */
382 supports_flag_zero_packet = kernel_version_ge(2,6,31);
383 if (-1 == supports_flag_zero_packet) {
384 usbi_err(ctx, "error checking for zero length packet support");
385 return LIBUSB_ERROR_OTHER;
389 if (supports_flag_zero_packet)
390 usbi_dbg("zero length packet flag supported");
392 if (-1 == sysfs_has_descriptors) {
393 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
394 sysfs_has_descriptors = kernel_version_ge(2,6,26);
395 if (-1 == sysfs_has_descriptors) {
396 usbi_err(ctx, "error checking for sysfs descriptors");
397 return LIBUSB_ERROR_OTHER;
401 if (-1 == sysfs_can_relate_devices) {
402 /* sysfs has busnum since Linux 2.6.22 */
403 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
404 if (-1 == sysfs_can_relate_devices) {
405 usbi_err(ctx, "error checking for sysfs busnum");
406 return LIBUSB_ERROR_OTHER;
410 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
411 r = stat(SYSFS_DEVICE_PATH, &statbuf);
412 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
413 usbi_warn(ctx, "sysfs not mounted");
414 sysfs_can_relate_devices = 0;
415 sysfs_has_descriptors = 0;
419 if (sysfs_can_relate_devices)
420 usbi_dbg("sysfs can relate devices");
422 if (sysfs_has_descriptors)
423 usbi_dbg("sysfs has complete descriptors");
425 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
427 if (init_count == 0) {
428 /* start up hotplug event handler */
429 r = linux_start_event_monitor();
431 if (r == LIBUSB_SUCCESS) {
432 r = linux_scan_devices(ctx);
433 if (r == LIBUSB_SUCCESS)
435 else if (init_count == 0)
436 linux_stop_event_monitor();
438 usbi_err(ctx, "error starting hotplug event monitor");
439 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
444 static void op_exit(void)
446 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
447 assert(init_count != 0);
449 /* tear down event handler */
450 (void)linux_stop_event_monitor();
452 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
455 static int linux_start_event_monitor(void)
457 #if defined(USE_UDEV)
458 return linux_udev_start_event_monitor();
460 return linux_netlink_start_event_monitor();
464 static int linux_stop_event_monitor(void)
466 #if defined(USE_UDEV)
467 return linux_udev_stop_event_monitor();
469 return linux_netlink_stop_event_monitor();
473 static int linux_scan_devices(struct libusb_context *ctx)
477 usbi_mutex_static_lock(&linux_hotplug_lock);
479 #if defined(USE_UDEV)
480 ret = linux_udev_scan_devices(ctx);
482 ret = linux_default_scan_devices(ctx);
485 usbi_mutex_static_unlock(&linux_hotplug_lock);
490 static void op_hotplug_poll(void)
492 #if defined(USE_UDEV)
493 linux_udev_hotplug_poll();
495 linux_netlink_hotplug_poll();
499 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
501 struct linux_device_priv *priv = _device_priv(dev);
502 char filename[PATH_MAX];
505 snprintf(filename, PATH_MAX, "%s/%s/%s",
506 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
507 fd = open(filename, O_RDONLY);
509 usbi_err(DEVICE_CTX(dev),
510 "open %s failed ret=%d errno=%d", filename, fd, errno);
511 return LIBUSB_ERROR_IO;
517 /* Note only suitable for attributes which always read >= 0, < 0 is error */
518 static int __read_sysfs_attr(struct libusb_context *ctx,
519 const char *devname, const char *attr)
521 char filename[PATH_MAX];
525 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
527 f = fopen(filename, "r");
529 if (errno == ENOENT) {
530 /* File doesn't exist. Assume the device has been
531 disconnected (see trac ticket #70). */
532 return LIBUSB_ERROR_NO_DEVICE;
534 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
535 return LIBUSB_ERROR_IO;
538 r = fscanf(f, "%d", &value);
541 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
542 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
545 usbi_err(ctx, "%s contains a negative value", filename);
546 return LIBUSB_ERROR_IO;
552 static int op_get_device_descriptor(struct libusb_device *dev,
553 unsigned char *buffer, int *host_endian)
555 struct linux_device_priv *priv = _device_priv(dev);
557 *host_endian = sysfs_has_descriptors ? 0 : 1;
558 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
563 /* read the bConfigurationValue for a device */
564 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
567 char tmp[4] = {0, 0, 0, 0};
572 fd = _open_sysfs_attr(dev, "bConfigurationValue");
576 r = read(fd, tmp, sizeof(tmp));
579 usbi_err(DEVICE_CTX(dev),
580 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
581 return LIBUSB_ERROR_IO;
583 usbi_dbg("device unconfigured");
588 if (tmp[sizeof(tmp) - 1] != 0) {
589 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
590 return LIBUSB_ERROR_IO;
591 } else if (tmp[0] == 0) {
592 usbi_err(DEVICE_CTX(dev), "no configuration value?");
593 return LIBUSB_ERROR_IO;
596 num = strtol(tmp, &endptr, 10);
598 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
599 return LIBUSB_ERROR_IO;
606 int linux_get_device_address (struct libusb_context *ctx, int detached,
607 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
608 const char *sys_name)
612 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
613 /* can't use sysfs to read the bus and device number if the
614 * device has been detached */
615 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
616 if (NULL == dev_node) {
617 return LIBUSB_ERROR_OTHER;
620 /* will this work with all supported kernel versions? */
621 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
622 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
623 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
624 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
627 return LIBUSB_SUCCESS;
630 usbi_dbg("scan %s", sys_name);
632 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
635 if (sysfs_attr > 255)
636 return LIBUSB_ERROR_INVALID_PARAM;
637 *busnum = (uint8_t) sysfs_attr;
639 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
642 if (sysfs_attr > 255)
643 return LIBUSB_ERROR_INVALID_PARAM;
645 *devaddr = (uint8_t) sysfs_attr;
647 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
649 return LIBUSB_SUCCESS;
652 /* Return offset of the next descriptor with the given type */
653 static int seek_to_next_descriptor(struct libusb_context *ctx,
654 uint8_t descriptor_type, unsigned char *buffer, int size)
656 struct usb_descriptor_header header;
659 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
661 return LIBUSB_ERROR_NOT_FOUND;
664 usbi_err(ctx, "short descriptor read %d/2", size);
665 return LIBUSB_ERROR_IO;
667 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
669 if (i && header.bDescriptorType == descriptor_type)
672 usbi_err(ctx, "bLength overflow by %d bytes", -size);
673 return LIBUSB_ERROR_IO;
676 /* Return offset to next config */
677 static int seek_to_next_config(struct libusb_context *ctx,
678 unsigned char *buffer, int size)
680 struct libusb_config_descriptor config;
683 return LIBUSB_ERROR_NOT_FOUND;
685 if (size < LIBUSB_DT_CONFIG_SIZE) {
686 usbi_err(ctx, "short descriptor read %d/%d",
687 size, LIBUSB_DT_CONFIG_SIZE);
688 return LIBUSB_ERROR_IO;
691 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
692 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
693 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
694 config.bDescriptorType);
695 return LIBUSB_ERROR_IO;
699 * In usbfs the config descriptors are config.wTotalLength bytes apart,
700 * with any short reads from the device appearing as holes in the file.
702 * In sysfs wTotalLength is ignored, instead the kernel returns a
703 * config descriptor with verified bLength fields, with descriptors
704 * with an invalid bLength removed.
706 if (sysfs_has_descriptors) {
707 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
709 if (next == LIBUSB_ERROR_NOT_FOUND)
714 if (next != config.wTotalLength)
715 usbi_warn(ctx, "config length mismatch wTotalLength "
716 "%d real %d", config.wTotalLength, next);
719 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
720 usbi_err(ctx, "invalid wTotalLength %d",
721 config.wTotalLength);
722 return LIBUSB_ERROR_IO;
723 } else if (config.wTotalLength > size) {
724 usbi_warn(ctx, "short descriptor read %d/%d",
725 size, config.wTotalLength);
728 return config.wTotalLength;
732 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
733 uint8_t value, unsigned char **buffer, int *host_endian)
735 struct libusb_context *ctx = DEVICE_CTX(dev);
736 struct linux_device_priv *priv = _device_priv(dev);
737 unsigned char *descriptors = priv->descriptors;
738 int size = priv->descriptors_len;
739 struct libusb_config_descriptor *config;
742 /* Unlike the device desc. config descs. are always in raw format */
745 /* Skip device header */
746 descriptors += DEVICE_DESC_LENGTH;
747 size -= DEVICE_DESC_LENGTH;
749 /* Seek till the config is found, or till "EOF" */
751 int next = seek_to_next_config(ctx, descriptors, size);
754 config = (struct libusb_config_descriptor *)descriptors;
755 if (config->bConfigurationValue == value) {
756 *buffer = descriptors;
764 static int op_get_active_config_descriptor(struct libusb_device *dev,
765 unsigned char *buffer, size_t len, int *host_endian)
768 unsigned char *config_desc;
770 if (sysfs_can_relate_devices) {
771 r = sysfs_get_active_config(dev, &config);
775 /* Use cached bConfigurationValue */
776 struct linux_device_priv *priv = _device_priv(dev);
777 config = priv->active_config;
780 return LIBUSB_ERROR_NOT_FOUND;
782 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
788 memcpy(buffer, config_desc, len);
792 static int op_get_config_descriptor(struct libusb_device *dev,
793 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
795 struct linux_device_priv *priv = _device_priv(dev);
796 unsigned char *descriptors = priv->descriptors;
797 int i, r, size = priv->descriptors_len;
799 /* Unlike the device desc. config descs. are always in raw format */
802 /* Skip device header */
803 descriptors += DEVICE_DESC_LENGTH;
804 size -= DEVICE_DESC_LENGTH;
806 /* Seek till the config is found, or till "EOF" */
808 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
811 if (i == config_index)
818 memcpy(buffer, descriptors, len);
822 /* send a control message to retrieve active configuration */
823 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
825 unsigned char active_config = 0;
828 struct usbfs_ctrltransfer ctrl = {
829 .bmRequestType = LIBUSB_ENDPOINT_IN,
830 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
835 .data = &active_config
838 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
841 return LIBUSB_ERROR_NO_DEVICE;
843 /* we hit this error path frequently with buggy devices :( */
844 usbi_warn(DEVICE_CTX(dev),
845 "get_configuration failed ret=%d errno=%d", r, errno);
846 return LIBUSB_ERROR_IO;
849 return active_config;
852 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
853 uint8_t devaddr, const char *sysfs_dir)
855 struct linux_device_priv *priv = _device_priv(dev);
856 struct libusb_context *ctx = DEVICE_CTX(dev);
857 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
861 dev->bus_number = busnum;
862 dev->device_address = devaddr;
865 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
866 if (!priv->sysfs_dir)
867 return LIBUSB_ERROR_NO_MEM;
868 strcpy(priv->sysfs_dir, sysfs_dir);
870 /* Note speed can contain 1.5, in this case __read_sysfs_attr
871 will stop parsing at the '.' and return 1 */
872 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
875 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
876 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
877 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
878 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
880 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
885 /* cache descriptors in memory */
886 if (sysfs_has_descriptors)
887 fd = _open_sysfs_attr(dev, "descriptors");
889 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
894 descriptors_size *= 2;
895 priv->descriptors = usbi_reallocf(priv->descriptors,
897 if (!priv->descriptors) {
899 return LIBUSB_ERROR_NO_MEM;
901 /* usbfs has holes in the file */
902 if (!sysfs_has_descriptors) {
903 memset(priv->descriptors + priv->descriptors_len,
904 0, descriptors_size - priv->descriptors_len);
906 r = read(fd, priv->descriptors + priv->descriptors_len,
907 descriptors_size - priv->descriptors_len);
909 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
912 return LIBUSB_ERROR_IO;
914 priv->descriptors_len += r;
915 } while (priv->descriptors_len == descriptors_size);
919 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
920 usbi_err(ctx, "short descriptor read (%d)",
921 priv->descriptors_len);
922 return LIBUSB_ERROR_IO;
925 if (sysfs_can_relate_devices)
926 return LIBUSB_SUCCESS;
928 /* cache active config */
929 fd = _get_usbfs_fd(dev, O_RDWR, 1);
931 /* cannot send a control message to determine the active
932 * config. just assume the first one is active. */
933 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
934 "active configuration descriptor");
935 if (priv->descriptors_len >=
936 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
937 struct libusb_config_descriptor config;
938 usbi_parse_descriptor(
939 priv->descriptors + DEVICE_DESC_LENGTH,
940 "bbwbbbbb", &config, 0);
941 priv->active_config = config.bConfigurationValue;
943 priv->active_config = -1; /* No config dt */
945 return LIBUSB_SUCCESS;
948 r = usbfs_get_active_config(dev, fd);
950 priv->active_config = r;
953 /* some buggy devices have a configuration 0, but we're
954 * reaching into the corner of a corner case here, so let's
955 * not support buggy devices in these circumstances.
956 * stick to the specs: a configuration value of 0 means
958 usbi_dbg("active cfg 0? assuming unconfigured device");
959 priv->active_config = -1;
961 } else if (r == LIBUSB_ERROR_IO) {
962 /* buggy devices sometimes fail to report their active config.
963 * assume unconfigured and continue the probing */
964 usbi_warn(ctx, "couldn't query active configuration, assuming"
966 priv->active_config = -1;
968 } /* else r < 0, just return the error code */
974 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
976 struct libusb_context *ctx = DEVICE_CTX(dev);
977 struct libusb_device *it;
978 char *parent_sysfs_dir, *tmp;
979 int ret, add_parent = 1;
981 /* XXX -- can we figure out the topology when using usbfs? */
982 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
983 /* either using usbfs or finding the parent of a root hub */
984 return LIBUSB_SUCCESS;
987 parent_sysfs_dir = strdup(sysfs_dir);
988 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
989 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
990 dev->port_number = atoi(tmp + 1);
993 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
995 free (parent_sysfs_dir);
996 return LIBUSB_SUCCESS;
999 /* is the parent a root hub? */
1000 if (NULL == strchr(parent_sysfs_dir, '-')) {
1001 tmp = parent_sysfs_dir;
1002 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1005 return LIBUSB_ERROR_NO_MEM;
1010 /* find the parent in the context */
1011 usbi_mutex_lock(&ctx->usb_devs_lock);
1012 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1013 struct linux_device_priv *priv = _device_priv(it);
1014 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1015 dev->parent_dev = libusb_ref_device(it);
1019 usbi_mutex_unlock(&ctx->usb_devs_lock);
1021 if (!dev->parent_dev && add_parent) {
1022 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1024 sysfs_scan_device(ctx, parent_sysfs_dir);
1029 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1030 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1032 free (parent_sysfs_dir);
1034 return LIBUSB_SUCCESS;
1037 int linux_enumerate_device(struct libusb_context *ctx,
1038 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1040 unsigned long session_id;
1041 struct libusb_device *dev;
1044 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1045 * will be reused. instead we should add a simple sysfs attribute with
1047 session_id = busnum << 8 | devaddr;
1048 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1051 if (usbi_get_device_by_session_id(ctx, session_id)) {
1052 /* device already exists in the context */
1053 usbi_dbg("session_id %ld already exists", session_id);
1054 return LIBUSB_SUCCESS;
1057 usbi_dbg("allocating new device for %d/%d (session %ld)",
1058 busnum, devaddr, session_id);
1059 dev = usbi_alloc_device(ctx, session_id);
1061 return LIBUSB_ERROR_NO_MEM;
1063 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1066 r = usbi_sanitize_device(dev);
1070 r = linux_get_parent_info(dev, sysfs_dir);
1075 libusb_unref_device(dev);
1077 usbi_connect_device(dev);
1082 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1084 struct libusb_context *ctx;
1086 usbi_mutex_static_lock(&active_contexts_lock);
1087 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1088 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1090 usbi_mutex_static_unlock(&active_contexts_lock);
1093 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1095 struct libusb_context *ctx;
1096 struct libusb_device *dev;
1097 unsigned long session_id = busnum << 8 | devaddr;
1099 usbi_mutex_static_lock(&active_contexts_lock);
1100 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1101 dev = usbi_get_device_by_session_id (ctx, session_id);
1103 usbi_disconnect_device (dev);
1105 usbi_dbg("device not found for session %x", session_id);
1108 usbi_mutex_static_unlock(&active_contexts_lock);
1111 #if !defined(USE_UDEV)
1112 /* open a bus directory and adds all discovered devices to the context */
1113 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1116 char dirpath[PATH_MAX];
1117 struct dirent *entry;
1118 int r = LIBUSB_ERROR_IO;
1120 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1121 usbi_dbg("%s", dirpath);
1122 dir = opendir(dirpath);
1124 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1125 /* FIXME: should handle valid race conditions like hub unplugged
1126 * during directory iteration - this is not an error */
1130 while ((entry = readdir(dir))) {
1133 if (entry->d_name[0] == '.')
1136 devaddr = atoi(entry->d_name);
1138 usbi_dbg("unknown dir entry %s", entry->d_name);
1142 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1143 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1154 static int usbfs_get_device_list(struct libusb_context *ctx)
1156 struct dirent *entry;
1157 DIR *buses = opendir(usbfs_path);
1161 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1162 return LIBUSB_ERROR_IO;
1165 while ((entry = readdir(buses))) {
1168 if (entry->d_name[0] == '.')
1173 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1176 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1178 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1182 busnum = atoi(entry->d_name);
1184 usbi_dbg("unknown dir entry %s", entry->d_name);
1188 r = usbfs_scan_busdir(ctx, busnum);
1200 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1202 uint8_t busnum, devaddr;
1205 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1206 if (LIBUSB_SUCCESS != ret) {
1210 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1214 #if !defined(USE_UDEV)
1215 static int sysfs_get_device_list(struct libusb_context *ctx)
1217 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1218 struct dirent *entry;
1219 int r = LIBUSB_ERROR_IO;
1222 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1226 while ((entry = readdir(devices))) {
1227 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1228 || strchr(entry->d_name, ':'))
1231 if (sysfs_scan_device(ctx, entry->d_name)) {
1232 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1243 static int linux_default_scan_devices (struct libusb_context *ctx)
1245 /* we can retrieve device list and descriptors from sysfs or usbfs.
1246 * sysfs is preferable, because if we use usbfs we end up resuming
1247 * any autosuspended USB devices. however, sysfs is not available
1248 * everywhere, so we need a usbfs fallback too.
1250 * as described in the "sysfs vs usbfs" comment at the top of this
1251 * file, sometimes we have sysfs but not enough information to
1252 * relate sysfs devices to usbfs nodes. op_init() determines the
1253 * adequacy of sysfs and sets sysfs_can_relate_devices.
1255 if (sysfs_can_relate_devices != 0)
1256 return sysfs_get_device_list(ctx);
1258 return usbfs_get_device_list(ctx);
1262 static int op_open(struct libusb_device_handle *handle)
1264 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1267 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1268 if (hpriv->fd < 0) {
1269 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1270 /* device will still be marked as attached if hotplug monitor thread
1271 * hasn't processed remove event yet */
1272 usbi_mutex_static_lock(&linux_hotplug_lock);
1273 if (handle->dev->attached) {
1274 usbi_dbg("open failed with no device, but device still attached");
1275 linux_device_disconnected(handle->dev->bus_number,
1276 handle->dev->device_address, NULL);
1278 usbi_mutex_static_unlock(&linux_hotplug_lock);
1283 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1285 if (errno == ENOTTY)
1286 usbi_dbg("getcap not available");
1288 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1290 if (supports_flag_zero_packet)
1291 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1292 if (supports_flag_bulk_continuation)
1293 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1296 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1299 static void op_close(struct libusb_device_handle *dev_handle)
1301 int fd = _device_handle_priv(dev_handle)->fd;
1302 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1306 static int op_get_configuration(struct libusb_device_handle *handle,
1311 if (sysfs_can_relate_devices) {
1312 r = sysfs_get_active_config(handle->dev, config);
1314 r = usbfs_get_active_config(handle->dev,
1315 _device_handle_priv(handle)->fd);
1320 if (*config == -1) {
1321 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1328 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1330 struct linux_device_priv *priv = _device_priv(handle->dev);
1331 int fd = _device_handle_priv(handle)->fd;
1332 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1334 if (errno == EINVAL)
1335 return LIBUSB_ERROR_NOT_FOUND;
1336 else if (errno == EBUSY)
1337 return LIBUSB_ERROR_BUSY;
1338 else if (errno == ENODEV)
1339 return LIBUSB_ERROR_NO_DEVICE;
1341 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1342 return LIBUSB_ERROR_OTHER;
1345 /* update our cached active config descriptor */
1346 priv->active_config = config;
1348 return LIBUSB_SUCCESS;
1351 static int claim_interface(struct libusb_device_handle *handle, int iface)
1353 int fd = _device_handle_priv(handle)->fd;
1354 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1356 if (errno == ENOENT)
1357 return LIBUSB_ERROR_NOT_FOUND;
1358 else if (errno == EBUSY)
1359 return LIBUSB_ERROR_BUSY;
1360 else if (errno == ENODEV)
1361 return LIBUSB_ERROR_NO_DEVICE;
1363 usbi_err(HANDLE_CTX(handle),
1364 "claim interface failed, error %d errno %d", r, errno);
1365 return LIBUSB_ERROR_OTHER;
1370 static int release_interface(struct libusb_device_handle *handle, int iface)
1372 int fd = _device_handle_priv(handle)->fd;
1373 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1375 if (errno == ENODEV)
1376 return LIBUSB_ERROR_NO_DEVICE;
1378 usbi_err(HANDLE_CTX(handle),
1379 "release interface failed, error %d errno %d", r, errno);
1380 return LIBUSB_ERROR_OTHER;
1385 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1388 int fd = _device_handle_priv(handle)->fd;
1389 struct usbfs_setinterface setintf;
1392 setintf.interface = iface;
1393 setintf.altsetting = altsetting;
1394 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1396 if (errno == EINVAL)
1397 return LIBUSB_ERROR_NOT_FOUND;
1398 else if (errno == ENODEV)
1399 return LIBUSB_ERROR_NO_DEVICE;
1401 usbi_err(HANDLE_CTX(handle),
1402 "setintf failed error %d errno %d", r, errno);
1403 return LIBUSB_ERROR_OTHER;
1409 static int op_clear_halt(struct libusb_device_handle *handle,
1410 unsigned char endpoint)
1412 int fd = _device_handle_priv(handle)->fd;
1413 unsigned int _endpoint = endpoint;
1414 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1416 if (errno == ENOENT)
1417 return LIBUSB_ERROR_NOT_FOUND;
1418 else if (errno == ENODEV)
1419 return LIBUSB_ERROR_NO_DEVICE;
1421 usbi_err(HANDLE_CTX(handle),
1422 "clear_halt failed error %d errno %d", r, errno);
1423 return LIBUSB_ERROR_OTHER;
1429 static int op_reset_device(struct libusb_device_handle *handle)
1431 int fd = _device_handle_priv(handle)->fd;
1434 /* Doing a device reset will cause the usbfs driver to get unbound
1435 from any interfaces it is bound to. By voluntarily unbinding
1436 the usbfs driver ourself, we stop the kernel from rebinding
1437 the interface after reset (which would end up with the interface
1438 getting bound to the in kernel driver if any). */
1439 for (i = 0; i < USB_MAXINTERFACES; i++) {
1440 if (handle->claimed_interfaces & (1L << i)) {
1441 release_interface(handle, i);
1445 usbi_mutex_lock(&handle->lock);
1446 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1448 if (errno == ENODEV) {
1449 ret = LIBUSB_ERROR_NOT_FOUND;
1453 usbi_err(HANDLE_CTX(handle),
1454 "reset failed error %d errno %d", r, errno);
1455 ret = LIBUSB_ERROR_OTHER;
1459 /* And re-claim any interfaces which were claimed before the reset */
1460 for (i = 0; i < USB_MAXINTERFACES; i++) {
1461 if (handle->claimed_interfaces & (1L << i)) {
1463 * A driver may have completed modprobing during
1464 * IOCTL_USBFS_RESET, and bound itself as soon as
1465 * IOCTL_USBFS_RESET released the device lock
1467 r = detach_kernel_driver_and_claim(handle, i);
1469 usbi_warn(HANDLE_CTX(handle),
1470 "failed to re-claim interface %d after reset: %s",
1471 i, libusb_error_name(r));
1472 handle->claimed_interfaces &= ~(1L << i);
1473 ret = LIBUSB_ERROR_NOT_FOUND;
1478 usbi_mutex_unlock(&handle->lock);
1482 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1485 int fd = _device_handle_priv(handle)->fd;
1486 struct usbfs_getdriver getdrv;
1489 getdrv.interface = interface;
1490 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1492 if (errno == ENODATA)
1494 else if (errno == ENODEV)
1495 return LIBUSB_ERROR_NO_DEVICE;
1497 usbi_err(HANDLE_CTX(handle),
1498 "get driver failed error %d errno %d", r, errno);
1499 return LIBUSB_ERROR_OTHER;
1502 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1505 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1508 int fd = _device_handle_priv(handle)->fd;
1509 struct usbfs_ioctl command;
1510 struct usbfs_getdriver getdrv;
1513 command.ifno = interface;
1514 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1515 command.data = NULL;
1517 getdrv.interface = interface;
1518 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1519 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1520 return LIBUSB_ERROR_NOT_FOUND;
1522 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1524 if (errno == ENODATA)
1525 return LIBUSB_ERROR_NOT_FOUND;
1526 else if (errno == EINVAL)
1527 return LIBUSB_ERROR_INVALID_PARAM;
1528 else if (errno == ENODEV)
1529 return LIBUSB_ERROR_NO_DEVICE;
1531 usbi_err(HANDLE_CTX(handle),
1532 "detach failed error %d errno %d", r, errno);
1533 return LIBUSB_ERROR_OTHER;
1539 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1542 int fd = _device_handle_priv(handle)->fd;
1543 struct usbfs_ioctl command;
1546 command.ifno = interface;
1547 command.ioctl_code = IOCTL_USBFS_CONNECT;
1548 command.data = NULL;
1550 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1552 if (errno == ENODATA)
1553 return LIBUSB_ERROR_NOT_FOUND;
1554 else if (errno == EINVAL)
1555 return LIBUSB_ERROR_INVALID_PARAM;
1556 else if (errno == ENODEV)
1557 return LIBUSB_ERROR_NO_DEVICE;
1558 else if (errno == EBUSY)
1559 return LIBUSB_ERROR_BUSY;
1561 usbi_err(HANDLE_CTX(handle),
1562 "attach failed error %d errno %d", r, errno);
1563 return LIBUSB_ERROR_OTHER;
1564 } else if (r == 0) {
1565 return LIBUSB_ERROR_NOT_FOUND;
1571 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1574 struct usbfs_disconnect_claim dc;
1575 int r, fd = _device_handle_priv(handle)->fd;
1577 dc.interface = interface;
1578 strcpy(dc.driver, "usbfs");
1579 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1580 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1581 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1587 return LIBUSB_ERROR_BUSY;
1589 return LIBUSB_ERROR_INVALID_PARAM;
1591 return LIBUSB_ERROR_NO_DEVICE;
1593 usbi_err(HANDLE_CTX(handle),
1594 "disconnect-and-claim failed errno %d", errno);
1595 return LIBUSB_ERROR_OTHER;
1598 /* Fallback code for kernels which don't support the
1599 disconnect-and-claim ioctl */
1600 r = op_detach_kernel_driver(handle, interface);
1601 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1604 return claim_interface(handle, interface);
1607 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1609 if (handle->auto_detach_kernel_driver)
1610 return detach_kernel_driver_and_claim(handle, iface);
1612 return claim_interface(handle, iface);
1615 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1619 r = release_interface(handle, iface);
1623 if (handle->auto_detach_kernel_driver)
1624 op_attach_kernel_driver(handle, iface);
1629 static void op_destroy_device(struct libusb_device *dev)
1631 struct linux_device_priv *priv = _device_priv(dev);
1632 if (priv->descriptors)
1633 free(priv->descriptors);
1634 if (priv->sysfs_dir)
1635 free(priv->sysfs_dir);
1638 /* URBs are discarded in reverse order of submission to avoid races. */
1639 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1641 struct libusb_transfer *transfer =
1642 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1643 struct linux_transfer_priv *tpriv =
1644 usbi_transfer_get_os_priv(itransfer);
1645 struct linux_device_handle_priv *dpriv =
1646 _device_handle_priv(transfer->dev_handle);
1648 struct usbfs_urb *urb;
1650 for (i = last_plus_one - 1; i >= first; i--) {
1651 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1652 urb = tpriv->iso_urbs[i];
1654 urb = &tpriv->urbs[i];
1656 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1659 if (EINVAL == errno) {
1660 usbi_dbg("URB not found --> assuming ready to be reaped");
1661 if (i == (last_plus_one - 1))
1662 ret = LIBUSB_ERROR_NOT_FOUND;
1663 } else if (ENODEV == errno) {
1664 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1665 ret = LIBUSB_ERROR_NO_DEVICE;
1667 usbi_warn(TRANSFER_CTX(transfer),
1668 "unrecognised discard errno %d", errno);
1669 ret = LIBUSB_ERROR_OTHER;
1675 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1678 for (i = 0; i < tpriv->num_urbs; i++) {
1679 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1685 free(tpriv->iso_urbs);
1686 tpriv->iso_urbs = NULL;
1689 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1690 unsigned char urb_type)
1692 struct libusb_transfer *transfer =
1693 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1694 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1695 struct linux_device_handle_priv *dpriv =
1696 _device_handle_priv(transfer->dev_handle);
1697 struct usbfs_urb *urbs;
1698 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1699 == LIBUSB_ENDPOINT_OUT;
1700 int bulk_buffer_len, use_bulk_continuation;
1706 return LIBUSB_ERROR_BUSY;
1708 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1709 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1710 return LIBUSB_ERROR_NOT_SUPPORTED;
1713 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1714 * around this by splitting large transfers into 16k blocks, and then
1715 * submit all urbs at once. it would be simpler to submit one urb at
1716 * a time, but there is a big performance gain doing it this way.
1718 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1719 * using arbritary large transfers can still be a bad idea though, as
1720 * the kernel needs to allocate physical contiguous memory for this,
1721 * which may fail for large buffers.
1723 * The kernel solves this problem by splitting the transfer into
1724 * blocks itself when the host-controller is scatter-gather capable
1725 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1727 * Last, there is the issue of short-transfers when splitting, for
1728 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1729 * is needed, but this is not always available.
1731 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1732 /* Good! Just submit everything in one go */
1733 bulk_buffer_len = transfer->length ? transfer->length : 1;
1734 use_bulk_continuation = 0;
1735 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1736 /* Split the transfers and use bulk-continuation to
1737 avoid issues with short-transfers */
1738 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1739 use_bulk_continuation = 1;
1740 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1741 /* Don't split, assume the kernel can alloc the buffer
1742 (otherwise the submit will fail with -ENOMEM) */
1743 bulk_buffer_len = transfer->length ? transfer->length : 1;
1744 use_bulk_continuation = 0;
1746 /* Bad, splitting without bulk-continuation, short transfers
1747 which end before the last urb will not work reliable! */
1748 /* Note we don't warn here as this is "normal" on kernels <
1749 2.6.32 and not a problem for most applications */
1750 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1751 use_bulk_continuation = 0;
1754 int num_urbs = transfer->length / bulk_buffer_len;
1755 int last_urb_partial = 0;
1757 if (transfer->length == 0) {
1759 } else if ((transfer->length % bulk_buffer_len) > 0) {
1760 last_urb_partial = 1;
1763 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1765 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1766 urbs = calloc(1, alloc_size);
1768 return LIBUSB_ERROR_NO_MEM;
1770 tpriv->num_urbs = num_urbs;
1771 tpriv->num_retired = 0;
1772 tpriv->reap_action = NORMAL;
1773 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1775 for (i = 0; i < num_urbs; i++) {
1776 struct usbfs_urb *urb = &urbs[i];
1777 urb->usercontext = itransfer;
1778 urb->type = urb_type;
1779 urb->endpoint = transfer->endpoint;
1780 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1781 /* don't set the short not ok flag for the last URB */
1782 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1783 urb->flags = USBFS_URB_SHORT_NOT_OK;
1784 if (i == num_urbs - 1 && last_urb_partial)
1785 urb->buffer_length = transfer->length % bulk_buffer_len;
1786 else if (transfer->length == 0)
1787 urb->buffer_length = 0;
1789 urb->buffer_length = bulk_buffer_len;
1791 if (i > 0 && use_bulk_continuation)
1792 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1794 /* we have already checked that the flag is supported */
1795 if (is_out && i == num_urbs - 1 &&
1796 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1797 urb->flags |= USBFS_URB_ZERO_PACKET;
1799 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1801 if (errno == ENODEV) {
1802 r = LIBUSB_ERROR_NO_DEVICE;
1804 usbi_err(TRANSFER_CTX(transfer),
1805 "submiturb failed error %d errno=%d", r, errno);
1806 r = LIBUSB_ERROR_IO;
1809 /* if the first URB submission fails, we can simply free up and
1810 * return failure immediately. */
1812 usbi_dbg("first URB failed, easy peasy");
1818 /* if it's not the first URB that failed, the situation is a bit
1819 * tricky. we may need to discard all previous URBs. there are
1821 * - discarding is asynchronous - discarded urbs will be reaped
1822 * later. the user must not have freed the transfer when the
1823 * discarded URBs are reaped, otherwise libusbx will be using
1825 * - the earlier URBs may have completed successfully and we do
1826 * not want to throw away any data.
1827 * - this URB failing may be no error; EREMOTEIO means that
1828 * this transfer simply didn't need all the URBs we submitted
1829 * so, we report that the transfer was submitted successfully and
1830 * in case of error we discard all previous URBs. later when
1831 * the final reap completes we can report error to the user,
1832 * or success if an earlier URB was completed successfully.
1834 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1836 /* The URBs we haven't submitted yet we count as already
1838 tpriv->num_retired += num_urbs - i;
1840 /* If we completed short then don't try to discard. */
1841 if (COMPLETED_EARLY == tpriv->reap_action)
1844 discard_urbs(itransfer, 0, i);
1846 usbi_dbg("reporting successful submission but waiting for %d "
1847 "discards before reporting error", i);
1855 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1857 struct libusb_transfer *transfer =
1858 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1859 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1860 struct linux_device_handle_priv *dpriv =
1861 _device_handle_priv(transfer->dev_handle);
1862 struct usbfs_urb **urbs;
1864 int num_packets = transfer->num_iso_packets;
1866 int this_urb_len = 0;
1868 int packet_offset = 0;
1869 unsigned int packet_len;
1870 unsigned char *urb_buffer = transfer->buffer;
1872 if (tpriv->iso_urbs)
1873 return LIBUSB_ERROR_BUSY;
1875 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1876 * into smaller units to meet such restriction, then fire off all the
1877 * units at once. it would be simpler if we just fired one unit at a time,
1878 * but there is a big performance gain through doing it this way.
1880 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1881 * using arbritary large transfers is still be a bad idea though, as
1882 * the kernel needs to allocate physical contiguous memory for this,
1883 * which may fail for large buffers.
1886 /* calculate how many URBs we need */
1887 for (i = 0; i < num_packets; i++) {
1888 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1889 packet_len = transfer->iso_packet_desc[i].length;
1891 if (packet_len > space_remaining) {
1893 this_urb_len = packet_len;
1895 this_urb_len += packet_len;
1898 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1900 alloc_size = num_urbs * sizeof(*urbs);
1901 urbs = calloc(1, alloc_size);
1903 return LIBUSB_ERROR_NO_MEM;
1905 tpriv->iso_urbs = urbs;
1906 tpriv->num_urbs = num_urbs;
1907 tpriv->num_retired = 0;
1908 tpriv->reap_action = NORMAL;
1909 tpriv->iso_packet_offset = 0;
1911 /* allocate + initialize each URB with the correct number of packets */
1912 for (i = 0; i < num_urbs; i++) {
1913 struct usbfs_urb *urb;
1914 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1915 int urb_packet_offset = 0;
1916 unsigned char *urb_buffer_orig = urb_buffer;
1920 /* swallow up all the packets we can fit into this URB */
1921 while (packet_offset < transfer->num_iso_packets) {
1922 packet_len = transfer->iso_packet_desc[packet_offset].length;
1923 if (packet_len <= space_remaining_in_urb) {
1925 urb_packet_offset++;
1927 space_remaining_in_urb -= packet_len;
1928 urb_buffer += packet_len;
1930 /* it can't fit, save it for the next URB */
1935 alloc_size = sizeof(*urb)
1936 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1937 urb = calloc(1, alloc_size);
1939 free_iso_urbs(tpriv);
1940 return LIBUSB_ERROR_NO_MEM;
1944 /* populate packet lengths */
1945 for (j = 0, k = packet_offset - urb_packet_offset;
1946 k < packet_offset; k++, j++) {
1947 packet_len = transfer->iso_packet_desc[k].length;
1948 urb->iso_frame_desc[j].length = packet_len;
1951 urb->usercontext = itransfer;
1952 urb->type = USBFS_URB_TYPE_ISO;
1953 /* FIXME: interface for non-ASAP data? */
1954 urb->flags = USBFS_URB_ISO_ASAP;
1955 urb->endpoint = transfer->endpoint;
1956 urb->number_of_packets = urb_packet_offset;
1957 urb->buffer = urb_buffer_orig;
1961 for (i = 0; i < num_urbs; i++) {
1962 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1964 if (errno == ENODEV) {
1965 r = LIBUSB_ERROR_NO_DEVICE;
1967 usbi_err(TRANSFER_CTX(transfer),
1968 "submiturb failed error %d errno=%d", r, errno);
1969 r = LIBUSB_ERROR_IO;
1972 /* if the first URB submission fails, we can simply free up and
1973 * return failure immediately. */
1975 usbi_dbg("first URB failed, easy peasy");
1976 free_iso_urbs(tpriv);
1980 /* if it's not the first URB that failed, the situation is a bit
1981 * tricky. we must discard all previous URBs. there are
1983 * - discarding is asynchronous - discarded urbs will be reaped
1984 * later. the user must not have freed the transfer when the
1985 * discarded URBs are reaped, otherwise libusbx will be using
1987 * - the earlier URBs may have completed successfully and we do
1988 * not want to throw away any data.
1989 * so, in this case we discard all the previous URBs BUT we report
1990 * that the transfer was submitted successfully. then later when
1991 * the final discard completes we can report error to the user.
1993 tpriv->reap_action = SUBMIT_FAILED;
1995 /* The URBs we haven't submitted yet we count as already
1997 tpriv->num_retired = num_urbs - i;
1998 discard_urbs(itransfer, 0, i);
2000 usbi_dbg("reporting successful submission but waiting for %d "
2001 "discards before reporting error", i);
2009 static int submit_control_transfer(struct usbi_transfer *itransfer)
2011 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2012 struct libusb_transfer *transfer =
2013 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2014 struct linux_device_handle_priv *dpriv =
2015 _device_handle_priv(transfer->dev_handle);
2016 struct usbfs_urb *urb;
2020 return LIBUSB_ERROR_BUSY;
2022 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2023 return LIBUSB_ERROR_INVALID_PARAM;
2025 urb = calloc(1, sizeof(struct usbfs_urb));
2027 return LIBUSB_ERROR_NO_MEM;
2029 tpriv->num_urbs = 1;
2030 tpriv->reap_action = NORMAL;
2032 urb->usercontext = itransfer;
2033 urb->type = USBFS_URB_TYPE_CONTROL;
2034 urb->endpoint = transfer->endpoint;
2035 urb->buffer = transfer->buffer;
2036 urb->buffer_length = transfer->length;
2038 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2042 if (errno == ENODEV)
2043 return LIBUSB_ERROR_NO_DEVICE;
2045 usbi_err(TRANSFER_CTX(transfer),
2046 "submiturb failed error %d errno=%d", r, errno);
2047 return LIBUSB_ERROR_IO;
2052 static int op_submit_transfer(struct usbi_transfer *itransfer)
2054 struct libusb_transfer *transfer =
2055 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2057 switch (transfer->type) {
2058 case LIBUSB_TRANSFER_TYPE_CONTROL:
2059 return submit_control_transfer(itransfer);
2060 case LIBUSB_TRANSFER_TYPE_BULK:
2061 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2062 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2063 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2064 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2065 return submit_iso_transfer(itransfer);
2067 usbi_err(TRANSFER_CTX(transfer),
2068 "unknown endpoint type %d", transfer->type);
2069 return LIBUSB_ERROR_INVALID_PARAM;
2073 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2075 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2076 struct libusb_transfer *transfer =
2077 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2079 switch (transfer->type) {
2080 case LIBUSB_TRANSFER_TYPE_BULK:
2081 if (tpriv->reap_action == ERROR)
2083 /* else, fall through */
2084 case LIBUSB_TRANSFER_TYPE_CONTROL:
2085 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2086 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2087 tpriv->reap_action = CANCELLED;
2090 usbi_err(TRANSFER_CTX(transfer),
2091 "unknown endpoint type %d", transfer->type);
2092 return LIBUSB_ERROR_INVALID_PARAM;
2096 return LIBUSB_ERROR_NOT_FOUND;
2098 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2101 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2103 struct libusb_transfer *transfer =
2104 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2105 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2107 /* urbs can be freed also in submit_transfer so lock mutex first */
2108 switch (transfer->type) {
2109 case LIBUSB_TRANSFER_TYPE_CONTROL:
2110 case LIBUSB_TRANSFER_TYPE_BULK:
2111 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2112 usbi_mutex_lock(&itransfer->lock);
2116 usbi_mutex_unlock(&itransfer->lock);
2118 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2119 usbi_mutex_lock(&itransfer->lock);
2120 if (tpriv->iso_urbs)
2121 free_iso_urbs(tpriv);
2122 usbi_mutex_unlock(&itransfer->lock);
2125 usbi_err(TRANSFER_CTX(transfer),
2126 "unknown endpoint type %d", transfer->type);
2130 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2131 struct usbfs_urb *urb)
2133 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2134 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2135 int urb_idx = urb - tpriv->urbs;
2137 usbi_mutex_lock(&itransfer->lock);
2138 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2139 urb_idx + 1, tpriv->num_urbs);
2141 tpriv->num_retired++;
2143 if (tpriv->reap_action != NORMAL) {
2144 /* cancelled, submit_fail, or completed early */
2145 usbi_dbg("abnormal reap: urb status %d", urb->status);
2147 /* even though we're in the process of cancelling, it's possible that
2148 * we may receive some data in these URBs that we don't want to lose.
2150 * 1. while the kernel is cancelling all the packets that make up an
2151 * URB, a few of them might complete. so we get back a successful
2152 * cancellation *and* some data.
2153 * 2. we receive a short URB which marks the early completion condition,
2154 * so we start cancelling the remaining URBs. however, we're too
2155 * slow and another URB completes (or at least completes partially).
2156 * (this can't happen since we always use BULK_CONTINUATION.)
2158 * When this happens, our objectives are not to lose any "surplus" data,
2159 * and also to stick it at the end of the previously-received data
2160 * (closing any holes), so that libusbx reports the total amount of
2161 * transferred data and presents it in a contiguous chunk.
2163 if (urb->actual_length > 0) {
2164 unsigned char *target = transfer->buffer + itransfer->transferred;
2165 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2166 if (urb->buffer != target) {
2167 usbi_dbg("moving surplus data from offset %d to offset %d",
2168 (unsigned char *) urb->buffer - transfer->buffer,
2169 target - transfer->buffer);
2170 memmove(target, urb->buffer, urb->actual_length);
2172 itransfer->transferred += urb->actual_length;
2175 if (tpriv->num_retired == tpriv->num_urbs) {
2176 usbi_dbg("abnormal reap: last URB handled, reporting");
2177 if (tpriv->reap_action != COMPLETED_EARLY &&
2178 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2179 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2185 itransfer->transferred += urb->actual_length;
2187 /* Many of these errors can occur on *any* urb of a multi-urb
2188 * transfer. When they do, we tear down the rest of the transfer.
2190 switch (urb->status) {
2193 case -EREMOTEIO: /* short transfer */
2195 case -ENOENT: /* cancelled */
2200 usbi_dbg("device removed");
2201 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2202 goto cancel_remaining;
2204 usbi_dbg("detected endpoint stall");
2205 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2206 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2207 goto cancel_remaining;
2209 /* overflow can only ever occur in the last urb */
2210 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2211 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2212 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2219 usbi_dbg("low level error %d", urb->status);
2220 tpriv->reap_action = ERROR;
2221 goto cancel_remaining;
2223 usbi_warn(ITRANSFER_CTX(itransfer),
2224 "unrecognised urb status %d", urb->status);
2225 tpriv->reap_action = ERROR;
2226 goto cancel_remaining;
2229 /* if we're the last urb or we got less data than requested then we're
2231 if (urb_idx == tpriv->num_urbs - 1) {
2232 usbi_dbg("last URB in transfer --> complete!");
2234 } else if (urb->actual_length < urb->buffer_length) {
2235 usbi_dbg("short transfer %d/%d --> complete!",
2236 urb->actual_length, urb->buffer_length);
2237 if (tpriv->reap_action == NORMAL)
2238 tpriv->reap_action = COMPLETED_EARLY;
2243 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2244 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2246 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2249 /* cancel remaining urbs and wait for their completion before
2250 * reporting results */
2251 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2254 usbi_mutex_unlock(&itransfer->lock);
2260 usbi_mutex_unlock(&itransfer->lock);
2261 return CANCELLED == tpriv->reap_action ?
2262 usbi_handle_transfer_cancellation(itransfer) :
2263 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2266 static int handle_iso_completion(struct usbi_transfer *itransfer,
2267 struct usbfs_urb *urb)
2269 struct libusb_transfer *transfer =
2270 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2271 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2272 int num_urbs = tpriv->num_urbs;
2275 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2277 usbi_mutex_lock(&itransfer->lock);
2278 for (i = 0; i < num_urbs; i++) {
2279 if (urb == tpriv->iso_urbs[i]) {
2285 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2286 usbi_mutex_unlock(&itransfer->lock);
2287 return LIBUSB_ERROR_NOT_FOUND;
2290 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2293 /* copy isochronous results back in */
2295 for (i = 0; i < urb->number_of_packets; i++) {
2296 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2297 struct libusb_iso_packet_descriptor *lib_desc =
2298 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2299 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2300 switch (urb_desc->status) {
2303 case -ENOENT: /* cancelled */
2308 usbi_dbg("device removed");
2309 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2312 usbi_dbg("detected endpoint stall");
2313 lib_desc->status = LIBUSB_TRANSFER_STALL;
2316 usbi_dbg("overflow error");
2317 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2325 usbi_dbg("low-level USB error %d", urb_desc->status);
2326 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2329 usbi_warn(TRANSFER_CTX(transfer),
2330 "unrecognised urb status %d", urb_desc->status);
2331 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2334 lib_desc->actual_length = urb_desc->actual_length;
2337 tpriv->num_retired++;
2339 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2340 usbi_dbg("CANCEL: urb status %d", urb->status);
2342 if (tpriv->num_retired == num_urbs) {
2343 usbi_dbg("CANCEL: last URB handled, reporting");
2344 free_iso_urbs(tpriv);
2345 if (tpriv->reap_action == CANCELLED) {
2346 usbi_mutex_unlock(&itransfer->lock);
2347 return usbi_handle_transfer_cancellation(itransfer);
2349 usbi_mutex_unlock(&itransfer->lock);
2350 return usbi_handle_transfer_completion(itransfer,
2351 LIBUSB_TRANSFER_ERROR);
2357 switch (urb->status) {
2360 case -ENOENT: /* cancelled */
2364 usbi_dbg("device removed");
2365 status = LIBUSB_TRANSFER_NO_DEVICE;
2368 usbi_warn(TRANSFER_CTX(transfer),
2369 "unrecognised urb status %d", urb->status);
2370 status = LIBUSB_TRANSFER_ERROR;
2374 /* if we're the last urb then we're done */
2375 if (urb_idx == num_urbs) {
2376 usbi_dbg("last URB in transfer --> complete!");
2377 free_iso_urbs(tpriv);
2378 usbi_mutex_unlock(&itransfer->lock);
2379 return usbi_handle_transfer_completion(itransfer, status);
2383 usbi_mutex_unlock(&itransfer->lock);
2387 static int handle_control_completion(struct usbi_transfer *itransfer,
2388 struct usbfs_urb *urb)
2390 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2393 usbi_mutex_lock(&itransfer->lock);
2394 usbi_dbg("handling completion status %d", urb->status);
2396 itransfer->transferred += urb->actual_length;
2398 if (tpriv->reap_action == CANCELLED) {
2399 if (urb->status != 0 && urb->status != -ENOENT)
2400 usbi_warn(ITRANSFER_CTX(itransfer),
2401 "cancel: unrecognised urb status %d", urb->status);
2404 usbi_mutex_unlock(&itransfer->lock);
2405 return usbi_handle_transfer_cancellation(itransfer);
2408 switch (urb->status) {
2410 status = LIBUSB_TRANSFER_COMPLETED;
2412 case -ENOENT: /* cancelled */
2413 status = LIBUSB_TRANSFER_CANCELLED;
2417 usbi_dbg("device removed");
2418 status = LIBUSB_TRANSFER_NO_DEVICE;
2421 usbi_dbg("unsupported control request");
2422 status = LIBUSB_TRANSFER_STALL;
2425 usbi_dbg("control overflow error");
2426 status = LIBUSB_TRANSFER_OVERFLOW;
2433 usbi_dbg("low-level bus error occurred");
2434 status = LIBUSB_TRANSFER_ERROR;
2437 usbi_warn(ITRANSFER_CTX(itransfer),
2438 "unrecognised urb status %d", urb->status);
2439 status = LIBUSB_TRANSFER_ERROR;
2445 usbi_mutex_unlock(&itransfer->lock);
2446 return usbi_handle_transfer_completion(itransfer, status);
2449 static int reap_for_handle(struct libusb_device_handle *handle)
2451 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2453 struct usbfs_urb *urb;
2454 struct usbi_transfer *itransfer;
2455 struct libusb_transfer *transfer;
2457 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2458 if (r == -1 && errno == EAGAIN)
2461 if (errno == ENODEV)
2462 return LIBUSB_ERROR_NO_DEVICE;
2464 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2466 return LIBUSB_ERROR_IO;
2469 itransfer = urb->usercontext;
2470 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2472 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2473 urb->actual_length);
2475 switch (transfer->type) {
2476 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2477 return handle_iso_completion(itransfer, urb);
2478 case LIBUSB_TRANSFER_TYPE_BULK:
2479 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2480 return handle_bulk_completion(itransfer, urb);
2481 case LIBUSB_TRANSFER_TYPE_CONTROL:
2482 return handle_control_completion(itransfer, urb);
2484 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2486 return LIBUSB_ERROR_OTHER;
2490 static int op_handle_events(struct libusb_context *ctx,
2491 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2496 usbi_mutex_lock(&ctx->open_devs_lock);
2497 for (i = 0; i < nfds && num_ready > 0; i++) {
2498 struct pollfd *pollfd = &fds[i];
2499 struct libusb_device_handle *handle;
2500 struct linux_device_handle_priv *hpriv = NULL;
2502 if (!pollfd->revents)
2506 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2507 hpriv = _device_handle_priv(handle);
2508 if (hpriv->fd == pollfd->fd)
2512 if (pollfd->revents & POLLERR) {
2513 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2514 usbi_handle_disconnect(handle);
2515 /* device will still be marked as attached if hotplug monitor thread
2516 * hasn't processed remove event yet */
2517 usbi_mutex_static_lock(&linux_hotplug_lock);
2518 if (handle->dev->attached)
2519 linux_device_disconnected(handle->dev->bus_number,
2520 handle->dev->device_address, NULL);
2521 usbi_mutex_static_unlock(&linux_hotplug_lock);
2526 r = reap_for_handle(handle);
2528 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2536 usbi_mutex_unlock(&ctx->open_devs_lock);
2540 static int op_clock_gettime(int clk_id, struct timespec *tp)
2543 case USBI_CLOCK_MONOTONIC:
2544 return clock_gettime(monotonic_clkid, tp);
2545 case USBI_CLOCK_REALTIME:
2546 return clock_gettime(CLOCK_REALTIME, tp);
2548 return LIBUSB_ERROR_INVALID_PARAM;
2552 #ifdef USBI_TIMERFD_AVAILABLE
2553 static clockid_t op_get_timerfd_clockid(void)
2555 return monotonic_clkid;
2560 const struct usbi_os_backend linux_usbfs_backend = {
2561 .name = "Linux usbfs",
2562 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2565 .get_device_list = NULL,
2566 .hotplug_poll = op_hotplug_poll,
2567 .get_device_descriptor = op_get_device_descriptor,
2568 .get_active_config_descriptor = op_get_active_config_descriptor,
2569 .get_config_descriptor = op_get_config_descriptor,
2570 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2574 .get_configuration = op_get_configuration,
2575 .set_configuration = op_set_configuration,
2576 .claim_interface = op_claim_interface,
2577 .release_interface = op_release_interface,
2579 .set_interface_altsetting = op_set_interface,
2580 .clear_halt = op_clear_halt,
2581 .reset_device = op_reset_device,
2583 .kernel_driver_active = op_kernel_driver_active,
2584 .detach_kernel_driver = op_detach_kernel_driver,
2585 .attach_kernel_driver = op_attach_kernel_driver,
2587 .destroy_device = op_destroy_device,
2589 .submit_transfer = op_submit_transfer,
2590 .cancel_transfer = op_cancel_transfer,
2591 .clear_transfer_priv = op_clear_transfer_priv,
2593 .handle_events = op_handle_events,
2595 .clock_gettime = op_clock_gettime,
2597 #ifdef USBI_TIMERFD_AVAILABLE
2598 .get_timerfd_clockid = op_get_timerfd_clockid,
2601 .device_priv_size = sizeof(struct linux_device_priv),
2602 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2603 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2604 .add_iso_packet_size = 0,