2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
6 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #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 volatile int init_count = 0;
123 /* Serialize hotplug start/stop, scan-devices, event-thread, and poll */
124 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
126 static int linux_start_event_monitor(void);
127 static int linux_stop_event_monitor(void);
128 static int linux_scan_devices(struct libusb_context *ctx);
129 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
130 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
132 #if !defined(USE_UDEV)
133 static int linux_default_scan_devices (struct libusb_context *ctx);
136 struct linux_device_priv {
138 unsigned char *descriptors;
140 int active_config; /* cache val for !sysfs_can_relate_devices */
143 struct linux_device_handle_priv {
150 /* submission failed after the first URB, so await cancellation/completion
151 * of all the others */
154 /* cancelled by user or timeout */
157 /* completed multi-URB transfer in non-final URB */
160 /* one or more urbs encountered a low-level error */
164 struct linux_transfer_priv {
166 struct usbfs_urb *urbs;
167 struct usbfs_urb **iso_urbs;
170 enum reap_action reap_action;
173 enum libusb_transfer_status reap_status;
175 /* next iso packet in user-supplied transfer to be populated */
176 int iso_packet_offset;
179 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
181 struct libusb_context *ctx = DEVICE_CTX(dev);
186 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
187 usbfs_path, dev->bus_number, dev->device_address);
189 snprintf(path, PATH_MAX, "%s/%03d/%03d",
190 usbfs_path, dev->bus_number, dev->device_address);
192 fd = open(path, mode);
194 return fd; /* Success */
197 usbi_err(ctx, "libusbx couldn't open USB device %s: %s",
198 path, strerror(errno));
199 if (errno == EACCES && mode == O_RDWR)
200 usbi_err(ctx, "libusbx requires write access to USB "
205 return LIBUSB_ERROR_ACCESS;
207 return LIBUSB_ERROR_NO_DEVICE;
208 return LIBUSB_ERROR_IO;
211 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
213 return (struct linux_device_priv *) dev->os_priv;
216 static struct linux_device_handle_priv *_device_handle_priv(
217 struct libusb_device_handle *handle)
219 return (struct linux_device_handle_priv *) handle->os_priv;
222 /* check dirent for a /dev/usbdev%d.%d name
223 * optionally return bus/device on success */
224 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
228 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
231 usbi_dbg("found: %s", entry->d_name);
239 static int check_usb_vfs(const char *dirname)
242 struct dirent *entry;
245 dir = opendir(dirname);
249 while ((entry = readdir(dir)) != NULL) {
250 if (entry->d_name[0] == '.')
253 /* We assume if we find any files that it must be the right place */
262 static const char *find_usbfs_path(void)
264 const char *path = "/dev/bus/usb";
265 const char *ret = NULL;
267 if (check_usb_vfs(path)) {
270 path = "/proc/bus/usb";
271 if (check_usb_vfs(path))
275 /* look for /dev/usbdev*.* if the normal places fail */
277 struct dirent *entry;
283 while ((entry = readdir(dir)) != NULL) {
284 if (_is_usbdev_entry(entry, NULL, NULL)) {
285 /* found one; that's enough */
296 usbi_dbg("found usbfs at %s", ret);
301 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
302 * seem to lack it). fall back to REALTIME if we have to. */
303 static clockid_t find_monotonic_clock(void)
305 #ifdef CLOCK_MONOTONIC
309 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
310 * because it's not available through timerfd */
311 r = clock_gettime(CLOCK_MONOTONIC, &ts);
313 return CLOCK_MONOTONIC;
314 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
317 return CLOCK_REALTIME;
320 static int kernel_version_ge(int major, int minor, int sublevel)
323 int atoms, kmajor, kminor, ksublevel;
327 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
336 /* kmajor == major */
338 return 0 == minor && 0 == sublevel;
344 /* kminor == minor */
346 return 0 == sublevel;
348 return ksublevel >= sublevel;
351 static int op_init(struct libusb_context *ctx)
356 usbfs_path = find_usbfs_path();
358 usbi_err(ctx, "could not find usbfs");
359 return LIBUSB_ERROR_OTHER;
362 if (monotonic_clkid == -1)
363 monotonic_clkid = find_monotonic_clock();
365 if (supports_flag_bulk_continuation == -1) {
366 /* bulk continuation URB flag available from Linux 2.6.32 */
367 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
368 if (supports_flag_bulk_continuation == -1) {
369 usbi_err(ctx, "error checking for bulk continuation support");
370 return LIBUSB_ERROR_OTHER;
374 if (supports_flag_bulk_continuation)
375 usbi_dbg("bulk continuation flag supported");
377 if (-1 == supports_flag_zero_packet) {
378 /* zero length packet URB flag fixed since Linux 2.6.31 */
379 supports_flag_zero_packet = kernel_version_ge(2,6,31);
380 if (-1 == supports_flag_zero_packet) {
381 usbi_err(ctx, "error checking for zero length packet support");
382 return LIBUSB_ERROR_OTHER;
386 if (supports_flag_zero_packet)
387 usbi_dbg("zero length packet flag supported");
389 if (-1 == sysfs_has_descriptors) {
390 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
391 sysfs_has_descriptors = kernel_version_ge(2,6,26);
392 if (-1 == sysfs_has_descriptors) {
393 usbi_err(ctx, "error checking for sysfs descriptors");
394 return LIBUSB_ERROR_OTHER;
398 if (-1 == sysfs_can_relate_devices) {
399 /* sysfs has busnum since Linux 2.6.22 */
400 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
401 if (-1 == sysfs_can_relate_devices) {
402 usbi_err(ctx, "error checking for sysfs busnum");
403 return LIBUSB_ERROR_OTHER;
407 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
408 r = stat(SYSFS_DEVICE_PATH, &statbuf);
409 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
410 usbi_warn(ctx, "sysfs not mounted");
411 sysfs_can_relate_devices = 0;
412 sysfs_has_descriptors = 0;
416 if (sysfs_can_relate_devices)
417 usbi_dbg("sysfs can relate devices");
419 if (sysfs_has_descriptors)
420 usbi_dbg("sysfs has complete descriptors");
422 usbi_mutex_static_lock(&linux_hotplug_lock);
424 if (init_count == 0) {
425 /* start up hotplug event handler */
426 r = linux_start_event_monitor();
428 if (r == LIBUSB_SUCCESS) {
429 r = linux_scan_devices(ctx);
430 if (r == LIBUSB_SUCCESS)
432 else if (init_count == 0)
433 linux_stop_event_monitor();
435 usbi_err(ctx, "error starting hotplug event monitor");
436 usbi_mutex_static_unlock(&linux_hotplug_lock);
441 static void op_exit(void)
443 usbi_mutex_static_lock(&linux_hotplug_lock);
444 assert(init_count != 0);
446 /* tear down event handler */
447 (void)linux_stop_event_monitor();
449 usbi_mutex_static_unlock(&linux_hotplug_lock);
452 static int linux_start_event_monitor(void)
454 #if defined(USE_UDEV)
455 return linux_udev_start_event_monitor();
457 return linux_netlink_start_event_monitor();
461 static int linux_stop_event_monitor(void)
463 #if defined(USE_UDEV)
464 return linux_udev_stop_event_monitor();
466 return linux_netlink_stop_event_monitor();
470 static int linux_scan_devices(struct libusb_context *ctx)
472 #if defined(USE_UDEV)
473 return linux_udev_scan_devices(ctx);
475 return linux_default_scan_devices(ctx);
479 static void op_hotplug_poll(void)
481 #if defined(USE_UDEV)
482 linux_udev_hotplug_poll();
484 linux_netlink_hotplug_poll();
488 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
490 struct linux_device_priv *priv = _device_priv(dev);
491 char filename[PATH_MAX];
494 snprintf(filename, PATH_MAX, "%s/%s/%s",
495 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
496 fd = open(filename, O_RDONLY);
498 usbi_err(DEVICE_CTX(dev),
499 "open %s failed ret=%d errno=%d", filename, fd, errno);
500 return LIBUSB_ERROR_IO;
506 /* Note only suitable for attributes which always read >= 0, < 0 is error */
507 static int __read_sysfs_attr(struct libusb_context *ctx,
508 const char *devname, const char *attr)
510 char filename[PATH_MAX];
514 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
516 f = fopen(filename, "r");
518 if (errno == ENOENT) {
519 /* File doesn't exist. Assume the device has been
520 disconnected (see trac ticket #70). */
521 return LIBUSB_ERROR_NO_DEVICE;
523 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
524 return LIBUSB_ERROR_IO;
527 r = fscanf(f, "%d", &value);
530 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
531 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
534 usbi_err(ctx, "%s contains a negative value", filename);
535 return LIBUSB_ERROR_IO;
541 static int op_get_device_descriptor(struct libusb_device *dev,
542 unsigned char *buffer, int *host_endian)
544 struct linux_device_priv *priv = _device_priv(dev);
546 *host_endian = sysfs_has_descriptors ? 0 : 1;
547 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
552 /* read the bConfigurationValue for a device */
553 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
556 char tmp[4] = {0, 0, 0, 0};
561 fd = _open_sysfs_attr(dev, "bConfigurationValue");
565 r = read(fd, tmp, sizeof(tmp));
568 usbi_err(DEVICE_CTX(dev),
569 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
570 return LIBUSB_ERROR_IO;
572 usbi_dbg("device unconfigured");
577 if (tmp[sizeof(tmp) - 1] != 0) {
578 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
579 return LIBUSB_ERROR_IO;
580 } else if (tmp[0] == 0) {
581 usbi_err(DEVICE_CTX(dev), "no configuration value?");
582 return LIBUSB_ERROR_IO;
585 num = strtol(tmp, &endptr, 10);
587 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
588 return LIBUSB_ERROR_IO;
595 int linux_get_device_address (struct libusb_context *ctx, int detached,
596 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
597 const char *sys_name)
599 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
600 /* can't use sysfs to read the bus and device number if the
601 * device has been detached */
602 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
603 if (NULL == dev_node) {
604 return LIBUSB_ERROR_OTHER;
607 /* will this work with all supported kernel versions? */
608 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
609 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
610 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
611 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
614 return LIBUSB_SUCCESS;
617 usbi_dbg("scan %s", sys_name);
619 *busnum = __read_sysfs_attr(ctx, sys_name, "busnum");
623 *devaddr = __read_sysfs_attr(ctx, sys_name, "devnum");
627 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
628 if (*busnum > 255 || *devaddr > 255)
629 return LIBUSB_ERROR_INVALID_PARAM;
631 return LIBUSB_SUCCESS;
634 /* Return offset of the next descriptor with the given type */
635 static int seek_to_next_descriptor(struct libusb_context *ctx,
636 uint8_t descriptor_type, unsigned char *buffer, int size)
638 struct usb_descriptor_header header;
641 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
643 return LIBUSB_ERROR_NOT_FOUND;
646 usbi_err(ctx, "short descriptor read %d/2", size);
647 return LIBUSB_ERROR_IO;
649 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
651 if (i && header.bDescriptorType == descriptor_type)
654 usbi_err(ctx, "bLength overflow by %d bytes", -size);
655 return LIBUSB_ERROR_IO;
658 /* Return offset to next config */
659 static int seek_to_next_config(struct libusb_context *ctx,
660 unsigned char *buffer, int size)
662 struct libusb_config_descriptor config;
665 return LIBUSB_ERROR_NOT_FOUND;
667 if (size < LIBUSB_DT_CONFIG_SIZE) {
668 usbi_err(ctx, "short descriptor read %d/%d",
669 size, LIBUSB_DT_CONFIG_SIZE);
670 return LIBUSB_ERROR_IO;
673 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
674 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
675 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
676 config.bDescriptorType);
677 return LIBUSB_ERROR_IO;
681 * In usbfs the config descriptors are config.wTotalLength bytes apart,
682 * with any short reads from the device appearing as holes in the file.
684 * In sysfs wTotalLength is ignored, instead the kernel returns a
685 * config descriptor with verified bLength fields, with descriptors
686 * with an invalid bLength removed.
688 if (sysfs_has_descriptors) {
689 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
691 if (next == LIBUSB_ERROR_NOT_FOUND)
696 if (next != config.wTotalLength)
697 usbi_warn(ctx, "config length mismatch wTotalLength "
698 "%d real %d", config.wTotalLength, next);
701 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
702 usbi_err(ctx, "invalid wTotalLength %d",
703 config.wTotalLength);
704 return LIBUSB_ERROR_IO;
705 } else if (config.wTotalLength > size) {
706 usbi_warn(ctx, "short descriptor read %d/%d",
707 size, config.wTotalLength);
710 return config.wTotalLength;
714 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
715 uint8_t value, unsigned char **buffer, int *host_endian)
717 struct libusb_context *ctx = DEVICE_CTX(dev);
718 struct linux_device_priv *priv = _device_priv(dev);
719 unsigned char *descriptors = priv->descriptors;
720 int size = priv->descriptors_len;
721 struct libusb_config_descriptor *config;
724 /* Unlike the device desc. config descs. are always in raw format */
727 /* Skip device header */
728 descriptors += DEVICE_DESC_LENGTH;
729 size -= DEVICE_DESC_LENGTH;
731 /* Seek till the config is found, or till "EOF" */
733 int next = seek_to_next_config(ctx, descriptors, size);
736 config = (struct libusb_config_descriptor *)descriptors;
737 if (config->bConfigurationValue == value) {
738 *buffer = descriptors;
746 static int op_get_active_config_descriptor(struct libusb_device *dev,
747 unsigned char *buffer, size_t len, int *host_endian)
750 unsigned char *config_desc;
752 if (sysfs_can_relate_devices) {
753 r = sysfs_get_active_config(dev, &config);
757 /* Use cached bConfigurationValue */
758 struct linux_device_priv *priv = _device_priv(dev);
759 config = priv->active_config;
762 return LIBUSB_ERROR_NOT_FOUND;
764 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
770 memcpy(buffer, config_desc, len);
774 static int op_get_config_descriptor(struct libusb_device *dev,
775 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
777 struct linux_device_priv *priv = _device_priv(dev);
778 unsigned char *descriptors = priv->descriptors;
779 int i, r, size = priv->descriptors_len;
781 /* Unlike the device desc. config descs. are always in raw format */
784 /* Skip device header */
785 descriptors += DEVICE_DESC_LENGTH;
786 size -= DEVICE_DESC_LENGTH;
788 /* Seek till the config is found, or till "EOF" */
790 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
793 if (i == config_index)
800 memcpy(buffer, descriptors, len);
804 /* send a control message to retrieve active configuration */
805 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
807 unsigned char active_config = 0;
810 struct usbfs_ctrltransfer ctrl = {
811 .bmRequestType = LIBUSB_ENDPOINT_IN,
812 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
817 .data = &active_config
820 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
823 return LIBUSB_ERROR_NO_DEVICE;
825 /* we hit this error path frequently with buggy devices :( */
826 usbi_warn(DEVICE_CTX(dev),
827 "get_configuration failed ret=%d errno=%d", r, errno);
828 return LIBUSB_ERROR_IO;
831 return active_config;
834 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
835 uint8_t devaddr, const char *sysfs_dir)
837 struct linux_device_priv *priv = _device_priv(dev);
838 struct libusb_context *ctx = DEVICE_CTX(dev);
839 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
843 dev->bus_number = busnum;
844 dev->device_address = devaddr;
847 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
848 if (!priv->sysfs_dir)
849 return LIBUSB_ERROR_NO_MEM;
850 strcpy(priv->sysfs_dir, sysfs_dir);
852 /* Note speed can contain 1.5, in this case __read_sysfs_attr
853 will stop parsing at the '.' and return 1 */
854 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
857 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
858 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
859 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
860 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
862 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
867 /* cache descriptors in memory */
868 if (sysfs_has_descriptors)
869 fd = _open_sysfs_attr(dev, "descriptors");
871 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
876 descriptors_size *= 2;
877 priv->descriptors = usbi_reallocf(priv->descriptors,
879 if (!priv->descriptors) {
881 return LIBUSB_ERROR_NO_MEM;
883 /* usbfs has holes in the file */
884 if (!sysfs_has_descriptors) {
885 memset(priv->descriptors + priv->descriptors_len,
886 0, descriptors_size - priv->descriptors_len);
888 r = read(fd, priv->descriptors + priv->descriptors_len,
889 descriptors_size - priv->descriptors_len);
891 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
894 return LIBUSB_ERROR_IO;
896 priv->descriptors_len += r;
897 } while (priv->descriptors_len == descriptors_size);
901 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
902 usbi_err(ctx, "short descriptor read (%d)",
903 priv->descriptors_len);
904 return LIBUSB_ERROR_IO;
907 if (sysfs_can_relate_devices)
908 return LIBUSB_SUCCESS;
910 /* cache active config */
911 fd = _get_usbfs_fd(dev, O_RDWR, 1);
913 /* cannot send a control message to determine the active
914 * config. just assume the first one is active. */
915 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
916 "active configuration descriptor");
917 if (priv->descriptors_len >=
918 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
919 struct libusb_config_descriptor config;
920 usbi_parse_descriptor(
921 priv->descriptors + DEVICE_DESC_LENGTH,
922 "bbwbbbbb", &config, 0);
923 priv->active_config = config.bConfigurationValue;
925 priv->active_config = -1; /* No config dt */
927 return LIBUSB_SUCCESS;
930 r = usbfs_get_active_config(dev, fd);
932 priv->active_config = r;
935 /* some buggy devices have a configuration 0, but we're
936 * reaching into the corner of a corner case here, so let's
937 * not support buggy devices in these circumstances.
938 * stick to the specs: a configuration value of 0 means
940 usbi_dbg("active cfg 0? assuming unconfigured device");
941 priv->active_config = -1;
943 } else if (r == LIBUSB_ERROR_IO) {
944 /* buggy devices sometimes fail to report their active config.
945 * assume unconfigured and continue the probing */
946 usbi_warn(ctx, "couldn't query active configuration, assuming"
948 priv->active_config = -1;
950 } /* else r < 0, just return the error code */
956 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
958 struct libusb_context *ctx = DEVICE_CTX(dev);
959 struct libusb_device *it;
960 char *parent_sysfs_dir, *tmp;
961 int ret, add_parent = 1;
963 /* XXX -- can we figure out the topology when using usbfs? */
964 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
965 /* either using usbfs or finding the parent of a root hub */
966 return LIBUSB_SUCCESS;
969 parent_sysfs_dir = strdup(sysfs_dir);
970 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
971 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
972 dev->port_number = atoi(tmp + 1);
975 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
977 free (parent_sysfs_dir);
978 return LIBUSB_SUCCESS;
981 /* is the parent a root hub? */
982 if (NULL == strchr(parent_sysfs_dir, '-')) {
983 tmp = parent_sysfs_dir;
984 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
987 return LIBUSB_ERROR_NO_MEM;
992 /* find the parent in the context */
993 usbi_mutex_lock(&ctx->usb_devs_lock);
994 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
995 struct linux_device_priv *priv = _device_priv(it);
996 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
997 dev->parent_dev = libusb_ref_device(it);
1001 usbi_mutex_unlock(&ctx->usb_devs_lock);
1003 if (!dev->parent_dev && add_parent) {
1004 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1006 sysfs_scan_device(ctx, parent_sysfs_dir);
1011 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1012 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1014 free (parent_sysfs_dir);
1016 return LIBUSB_SUCCESS;
1019 int linux_enumerate_device(struct libusb_context *ctx,
1020 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1022 unsigned long session_id;
1023 struct libusb_device *dev;
1026 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1027 * will be reused. instead we should add a simple sysfs attribute with
1029 session_id = busnum << 8 | devaddr;
1030 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1033 if (usbi_get_device_by_session_id(ctx, session_id)) {
1034 /* device already exists in the context */
1035 usbi_dbg("session_id %ld already exists", session_id);
1036 return LIBUSB_SUCCESS;
1039 usbi_dbg("allocating new device for %d/%d (session %ld)",
1040 busnum, devaddr, session_id);
1041 dev = usbi_alloc_device(ctx, session_id);
1043 return LIBUSB_ERROR_NO_MEM;
1045 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1048 r = usbi_sanitize_device(dev);
1052 r = linux_get_parent_info(dev, sysfs_dir);
1057 libusb_unref_device(dev);
1059 usbi_connect_device(dev);
1064 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1066 struct libusb_context *ctx;
1068 usbi_mutex_static_lock(&active_contexts_lock);
1069 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1070 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1072 usbi_mutex_static_unlock(&active_contexts_lock);
1075 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1077 struct libusb_context *ctx;
1078 struct libusb_device *dev;
1079 unsigned long session_id = busnum << 8 | devaddr;
1081 usbi_mutex_static_lock(&active_contexts_lock);
1082 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1083 dev = usbi_get_device_by_session_id (ctx, session_id);
1085 usbi_disconnect_device (dev);
1087 usbi_dbg("device not found for session %x", session_id);
1090 usbi_mutex_static_unlock(&active_contexts_lock);
1093 #if !defined(USE_UDEV)
1094 /* open a bus directory and adds all discovered devices to the context */
1095 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1098 char dirpath[PATH_MAX];
1099 struct dirent *entry;
1100 int r = LIBUSB_ERROR_IO;
1102 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1103 usbi_dbg("%s", dirpath);
1104 dir = opendir(dirpath);
1106 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1107 /* FIXME: should handle valid race conditions like hub unplugged
1108 * during directory iteration - this is not an error */
1112 while ((entry = readdir(dir))) {
1115 if (entry->d_name[0] == '.')
1118 devaddr = atoi(entry->d_name);
1120 usbi_dbg("unknown dir entry %s", entry->d_name);
1124 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1125 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1136 static int usbfs_get_device_list(struct libusb_context *ctx)
1138 struct dirent *entry;
1139 DIR *buses = opendir(usbfs_path);
1143 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1144 return LIBUSB_ERROR_IO;
1147 while ((entry = readdir(buses))) {
1150 if (entry->d_name[0] == '.')
1155 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1158 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1160 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1164 busnum = atoi(entry->d_name);
1166 usbi_dbg("unknown dir entry %s", entry->d_name);
1170 r = usbfs_scan_busdir(ctx, busnum);
1182 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1184 uint8_t busnum, devaddr;
1187 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1188 if (LIBUSB_SUCCESS != ret) {
1192 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1196 #if !defined(USE_UDEV)
1197 static int sysfs_get_device_list(struct libusb_context *ctx)
1199 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1200 struct dirent *entry;
1201 int r = LIBUSB_ERROR_IO;
1204 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1208 while ((entry = readdir(devices))) {
1209 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1210 || strchr(entry->d_name, ':'))
1213 if (sysfs_scan_device(ctx, entry->d_name)) {
1214 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1225 static int linux_default_scan_devices (struct libusb_context *ctx)
1227 /* we can retrieve device list and descriptors from sysfs or usbfs.
1228 * sysfs is preferable, because if we use usbfs we end up resuming
1229 * any autosuspended USB devices. however, sysfs is not available
1230 * everywhere, so we need a usbfs fallback too.
1232 * as described in the "sysfs vs usbfs" comment at the top of this
1233 * file, sometimes we have sysfs but not enough information to
1234 * relate sysfs devices to usbfs nodes. op_init() determines the
1235 * adequacy of sysfs and sets sysfs_can_relate_devices.
1237 if (sysfs_can_relate_devices != 0)
1238 return sysfs_get_device_list(ctx);
1240 return usbfs_get_device_list(ctx);
1244 static int op_open(struct libusb_device_handle *handle)
1246 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1249 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1253 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1255 if (errno == ENOTTY)
1256 usbi_dbg("getcap not available");
1258 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1260 if (supports_flag_zero_packet)
1261 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1262 if (supports_flag_bulk_continuation)
1263 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1266 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1269 static void op_close(struct libusb_device_handle *dev_handle)
1271 int fd = _device_handle_priv(dev_handle)->fd;
1272 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1276 static int op_get_configuration(struct libusb_device_handle *handle,
1281 if (sysfs_can_relate_devices) {
1282 r = sysfs_get_active_config(handle->dev, config);
1284 r = usbfs_get_active_config(handle->dev,
1285 _device_handle_priv(handle)->fd);
1290 if (*config == -1) {
1291 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1298 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1300 struct linux_device_priv *priv = _device_priv(handle->dev);
1301 int fd = _device_handle_priv(handle)->fd;
1302 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1304 if (errno == EINVAL)
1305 return LIBUSB_ERROR_NOT_FOUND;
1306 else if (errno == EBUSY)
1307 return LIBUSB_ERROR_BUSY;
1308 else if (errno == ENODEV)
1309 return LIBUSB_ERROR_NO_DEVICE;
1311 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1312 return LIBUSB_ERROR_OTHER;
1315 /* update our cached active config descriptor */
1316 priv->active_config = config;
1318 return LIBUSB_SUCCESS;
1321 static int claim_interface(struct libusb_device_handle *handle, int iface)
1323 int fd = _device_handle_priv(handle)->fd;
1324 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1326 if (errno == ENOENT)
1327 return LIBUSB_ERROR_NOT_FOUND;
1328 else if (errno == EBUSY)
1329 return LIBUSB_ERROR_BUSY;
1330 else if (errno == ENODEV)
1331 return LIBUSB_ERROR_NO_DEVICE;
1333 usbi_err(HANDLE_CTX(handle),
1334 "claim interface failed, error %d errno %d", r, errno);
1335 return LIBUSB_ERROR_OTHER;
1340 static int release_interface(struct libusb_device_handle *handle, int iface)
1342 int fd = _device_handle_priv(handle)->fd;
1343 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1345 if (errno == ENODEV)
1346 return LIBUSB_ERROR_NO_DEVICE;
1348 usbi_err(HANDLE_CTX(handle),
1349 "release interface failed, error %d errno %d", r, errno);
1350 return LIBUSB_ERROR_OTHER;
1355 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1358 int fd = _device_handle_priv(handle)->fd;
1359 struct usbfs_setinterface setintf;
1362 setintf.interface = iface;
1363 setintf.altsetting = altsetting;
1364 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1366 if (errno == EINVAL)
1367 return LIBUSB_ERROR_NOT_FOUND;
1368 else if (errno == ENODEV)
1369 return LIBUSB_ERROR_NO_DEVICE;
1371 usbi_err(HANDLE_CTX(handle),
1372 "setintf failed error %d errno %d", r, errno);
1373 return LIBUSB_ERROR_OTHER;
1379 static int op_clear_halt(struct libusb_device_handle *handle,
1380 unsigned char endpoint)
1382 int fd = _device_handle_priv(handle)->fd;
1383 unsigned int _endpoint = endpoint;
1384 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1386 if (errno == ENOENT)
1387 return LIBUSB_ERROR_NOT_FOUND;
1388 else if (errno == ENODEV)
1389 return LIBUSB_ERROR_NO_DEVICE;
1391 usbi_err(HANDLE_CTX(handle),
1392 "clear_halt failed error %d errno %d", r, errno);
1393 return LIBUSB_ERROR_OTHER;
1399 static int op_reset_device(struct libusb_device_handle *handle)
1401 int fd = _device_handle_priv(handle)->fd;
1404 /* Doing a device reset will cause the usbfs driver to get unbound
1405 from any interfaces it is bound to. By voluntarily unbinding
1406 the usbfs driver ourself, we stop the kernel from rebinding
1407 the interface after reset (which would end up with the interface
1408 getting bound to the in kernel driver if any). */
1409 for (i = 0; i < USB_MAXINTERFACES; i++) {
1410 if (handle->claimed_interfaces & (1L << i)) {
1411 release_interface(handle, i);
1415 usbi_mutex_lock(&handle->lock);
1416 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1418 if (errno == ENODEV) {
1419 ret = LIBUSB_ERROR_NOT_FOUND;
1423 usbi_err(HANDLE_CTX(handle),
1424 "reset failed error %d errno %d", r, errno);
1425 ret = LIBUSB_ERROR_OTHER;
1429 /* And re-claim any interfaces which were claimed before the reset */
1430 for (i = 0; i < USB_MAXINTERFACES; i++) {
1431 if (handle->claimed_interfaces & (1L << i)) {
1433 * A driver may have completed modprobing during
1434 * IOCTL_USBFS_RESET, and bound itself as soon as
1435 * IOCTL_USBFS_RESET released the device lock
1437 r = detach_kernel_driver_and_claim(handle, i);
1439 usbi_warn(HANDLE_CTX(handle),
1440 "failed to re-claim interface %d after reset: %s",
1441 i, libusb_error_name(r));
1442 handle->claimed_interfaces &= ~(1L << i);
1443 ret = LIBUSB_ERROR_NOT_FOUND;
1448 usbi_mutex_unlock(&handle->lock);
1452 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1455 int fd = _device_handle_priv(handle)->fd;
1456 struct usbfs_getdriver getdrv;
1459 getdrv.interface = interface;
1460 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1462 if (errno == ENODATA)
1464 else if (errno == ENODEV)
1465 return LIBUSB_ERROR_NO_DEVICE;
1467 usbi_err(HANDLE_CTX(handle),
1468 "get driver failed error %d errno %d", r, errno);
1469 return LIBUSB_ERROR_OTHER;
1472 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1475 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1478 int fd = _device_handle_priv(handle)->fd;
1479 struct usbfs_ioctl command;
1480 struct usbfs_getdriver getdrv;
1483 command.ifno = interface;
1484 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1485 command.data = NULL;
1487 getdrv.interface = interface;
1488 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1489 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1490 return LIBUSB_ERROR_NOT_FOUND;
1492 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1494 if (errno == ENODATA)
1495 return LIBUSB_ERROR_NOT_FOUND;
1496 else if (errno == EINVAL)
1497 return LIBUSB_ERROR_INVALID_PARAM;
1498 else if (errno == ENODEV)
1499 return LIBUSB_ERROR_NO_DEVICE;
1501 usbi_err(HANDLE_CTX(handle),
1502 "detach failed error %d errno %d", r, errno);
1503 return LIBUSB_ERROR_OTHER;
1509 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1512 int fd = _device_handle_priv(handle)->fd;
1513 struct usbfs_ioctl command;
1516 command.ifno = interface;
1517 command.ioctl_code = IOCTL_USBFS_CONNECT;
1518 command.data = NULL;
1520 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1522 if (errno == ENODATA)
1523 return LIBUSB_ERROR_NOT_FOUND;
1524 else if (errno == EINVAL)
1525 return LIBUSB_ERROR_INVALID_PARAM;
1526 else if (errno == ENODEV)
1527 return LIBUSB_ERROR_NO_DEVICE;
1528 else if (errno == EBUSY)
1529 return LIBUSB_ERROR_BUSY;
1531 usbi_err(HANDLE_CTX(handle),
1532 "attach failed error %d errno %d", r, errno);
1533 return LIBUSB_ERROR_OTHER;
1534 } else if (r == 0) {
1535 return LIBUSB_ERROR_NOT_FOUND;
1541 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1544 struct usbfs_disconnect_claim dc;
1545 int r, fd = _device_handle_priv(handle)->fd;
1547 dc.interface = interface;
1548 strcpy(dc.driver, "usbfs");
1549 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1550 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1551 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1557 return LIBUSB_ERROR_BUSY;
1559 return LIBUSB_ERROR_INVALID_PARAM;
1561 return LIBUSB_ERROR_NO_DEVICE;
1563 usbi_err(HANDLE_CTX(handle),
1564 "disconnect-and-claim failed errno %d", errno);
1565 return LIBUSB_ERROR_OTHER;
1568 /* Fallback code for kernels which don't support the
1569 disconnect-and-claim ioctl */
1570 r = op_detach_kernel_driver(handle, interface);
1571 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1574 return claim_interface(handle, interface);
1577 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1579 if (handle->auto_detach_kernel_driver)
1580 return detach_kernel_driver_and_claim(handle, iface);
1582 return claim_interface(handle, iface);
1585 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1589 r = release_interface(handle, iface);
1593 if (handle->auto_detach_kernel_driver)
1594 op_attach_kernel_driver(handle, iface);
1599 static void op_destroy_device(struct libusb_device *dev)
1601 struct linux_device_priv *priv = _device_priv(dev);
1602 if (priv->descriptors)
1603 free(priv->descriptors);
1604 if (priv->sysfs_dir)
1605 free(priv->sysfs_dir);
1608 /* URBs are discarded in reverse order of submission to avoid races. */
1609 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1611 struct libusb_transfer *transfer =
1612 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1613 struct linux_transfer_priv *tpriv =
1614 usbi_transfer_get_os_priv(itransfer);
1615 struct linux_device_handle_priv *dpriv =
1616 _device_handle_priv(transfer->dev_handle);
1618 struct usbfs_urb *urb;
1620 for (i = last_plus_one - 1; i >= first; i--) {
1621 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1622 urb = tpriv->iso_urbs[i];
1624 urb = &tpriv->urbs[i];
1626 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1629 if (EINVAL == errno) {
1630 usbi_dbg("URB not found --> assuming ready to be reaped");
1631 if (i == (last_plus_one - 1))
1632 ret = LIBUSB_ERROR_NOT_FOUND;
1633 } else if (ENODEV == errno) {
1634 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1635 ret = LIBUSB_ERROR_NO_DEVICE;
1637 usbi_warn(TRANSFER_CTX(transfer),
1638 "unrecognised discard errno %d", errno);
1639 ret = LIBUSB_ERROR_OTHER;
1645 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1648 for (i = 0; i < tpriv->num_urbs; i++) {
1649 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1655 free(tpriv->iso_urbs);
1656 tpriv->iso_urbs = NULL;
1659 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1660 unsigned char urb_type)
1662 struct libusb_transfer *transfer =
1663 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1664 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1665 struct linux_device_handle_priv *dpriv =
1666 _device_handle_priv(transfer->dev_handle);
1667 struct usbfs_urb *urbs;
1668 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1669 == LIBUSB_ENDPOINT_OUT;
1670 int bulk_buffer_len, use_bulk_continuation;
1676 return LIBUSB_ERROR_BUSY;
1678 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1679 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1680 return LIBUSB_ERROR_NOT_SUPPORTED;
1683 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1684 * around this by splitting large transfers into 16k blocks, and then
1685 * submit all urbs at once. it would be simpler to submit one urb at
1686 * a time, but there is a big performance gain doing it this way.
1688 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1689 * using arbritary large transfers can still be a bad idea though, as
1690 * the kernel needs to allocate physical contiguous memory for this,
1691 * which may fail for large buffers.
1693 * The kernel solves this problem by splitting the transfer into
1694 * blocks itself when the host-controller is scatter-gather capable
1695 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1697 * Last, there is the issue of short-transfers when splitting, for
1698 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1699 * is needed, but this is not always available.
1701 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1702 /* Good! Just submit everything in one go */
1703 bulk_buffer_len = transfer->length ? transfer->length : 1;
1704 use_bulk_continuation = 0;
1705 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1706 /* Split the transfers and use bulk-continuation to
1707 avoid issues with short-transfers */
1708 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1709 use_bulk_continuation = 1;
1710 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1711 /* Don't split, assume the kernel can alloc the buffer
1712 (otherwise the submit will fail with -ENOMEM) */
1713 bulk_buffer_len = transfer->length ? transfer->length : 1;
1714 use_bulk_continuation = 0;
1716 /* Bad, splitting without bulk-continuation, short transfers
1717 which end before the last urb will not work reliable! */
1718 /* Note we don't warn here as this is "normal" on kernels <
1719 2.6.32 and not a problem for most applications */
1720 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1721 use_bulk_continuation = 0;
1724 int num_urbs = transfer->length / bulk_buffer_len;
1725 int last_urb_partial = 0;
1727 if (transfer->length == 0) {
1729 } else if ((transfer->length % bulk_buffer_len) > 0) {
1730 last_urb_partial = 1;
1733 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1735 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1736 urbs = calloc(1, alloc_size);
1738 return LIBUSB_ERROR_NO_MEM;
1740 tpriv->num_urbs = num_urbs;
1741 tpriv->num_retired = 0;
1742 tpriv->reap_action = NORMAL;
1743 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1745 for (i = 0; i < num_urbs; i++) {
1746 struct usbfs_urb *urb = &urbs[i];
1747 urb->usercontext = itransfer;
1748 urb->type = urb_type;
1749 urb->endpoint = transfer->endpoint;
1750 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1751 /* don't set the short not ok flag for the last URB */
1752 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1753 urb->flags = USBFS_URB_SHORT_NOT_OK;
1754 if (i == num_urbs - 1 && last_urb_partial)
1755 urb->buffer_length = transfer->length % bulk_buffer_len;
1756 else if (transfer->length == 0)
1757 urb->buffer_length = 0;
1759 urb->buffer_length = bulk_buffer_len;
1761 if (i > 0 && use_bulk_continuation)
1762 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1764 /* we have already checked that the flag is supported */
1765 if (is_out && i == num_urbs - 1 &&
1766 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1767 urb->flags |= USBFS_URB_ZERO_PACKET;
1769 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1771 if (errno == ENODEV) {
1772 r = LIBUSB_ERROR_NO_DEVICE;
1774 usbi_err(TRANSFER_CTX(transfer),
1775 "submiturb failed error %d errno=%d", r, errno);
1776 r = LIBUSB_ERROR_IO;
1779 /* if the first URB submission fails, we can simply free up and
1780 * return failure immediately. */
1782 usbi_dbg("first URB failed, easy peasy");
1788 /* if it's not the first URB that failed, the situation is a bit
1789 * tricky. we may need to discard all previous URBs. there are
1791 * - discarding is asynchronous - discarded urbs will be reaped
1792 * later. the user must not have freed the transfer when the
1793 * discarded URBs are reaped, otherwise libusbx will be using
1795 * - the earlier URBs may have completed successfully and we do
1796 * not want to throw away any data.
1797 * - this URB failing may be no error; EREMOTEIO means that
1798 * this transfer simply didn't need all the URBs we submitted
1799 * so, we report that the transfer was submitted successfully and
1800 * in case of error we discard all previous URBs. later when
1801 * the final reap completes we can report error to the user,
1802 * or success if an earlier URB was completed successfully.
1804 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1806 /* The URBs we haven't submitted yet we count as already
1808 tpriv->num_retired += num_urbs - i;
1810 /* If we completed short then don't try to discard. */
1811 if (COMPLETED_EARLY == tpriv->reap_action)
1814 discard_urbs(itransfer, 0, i);
1816 usbi_dbg("reporting successful submission but waiting for %d "
1817 "discards before reporting error", i);
1825 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1827 struct libusb_transfer *transfer =
1828 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1829 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1830 struct linux_device_handle_priv *dpriv =
1831 _device_handle_priv(transfer->dev_handle);
1832 struct usbfs_urb **urbs;
1834 int num_packets = transfer->num_iso_packets;
1836 int this_urb_len = 0;
1838 int packet_offset = 0;
1839 unsigned int packet_len;
1840 unsigned char *urb_buffer = transfer->buffer;
1842 if (tpriv->iso_urbs)
1843 return LIBUSB_ERROR_BUSY;
1845 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1846 * into smaller units to meet such restriction, then fire off all the
1847 * units at once. it would be simpler if we just fired one unit at a time,
1848 * but there is a big performance gain through doing it this way.
1850 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1851 * using arbritary large transfers is still be a bad idea though, as
1852 * the kernel needs to allocate physical contiguous memory for this,
1853 * which may fail for large buffers.
1856 /* calculate how many URBs we need */
1857 for (i = 0; i < num_packets; i++) {
1858 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1859 packet_len = transfer->iso_packet_desc[i].length;
1861 if (packet_len > space_remaining) {
1863 this_urb_len = packet_len;
1865 this_urb_len += packet_len;
1868 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1870 alloc_size = num_urbs * sizeof(*urbs);
1871 urbs = calloc(1, alloc_size);
1873 return LIBUSB_ERROR_NO_MEM;
1875 tpriv->iso_urbs = urbs;
1876 tpriv->num_urbs = num_urbs;
1877 tpriv->num_retired = 0;
1878 tpriv->reap_action = NORMAL;
1879 tpriv->iso_packet_offset = 0;
1881 /* allocate + initialize each URB with the correct number of packets */
1882 for (i = 0; i < num_urbs; i++) {
1883 struct usbfs_urb *urb;
1884 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1885 int urb_packet_offset = 0;
1886 unsigned char *urb_buffer_orig = urb_buffer;
1890 /* swallow up all the packets we can fit into this URB */
1891 while (packet_offset < transfer->num_iso_packets) {
1892 packet_len = transfer->iso_packet_desc[packet_offset].length;
1893 if (packet_len <= space_remaining_in_urb) {
1895 urb_packet_offset++;
1897 space_remaining_in_urb -= packet_len;
1898 urb_buffer += packet_len;
1900 /* it can't fit, save it for the next URB */
1905 alloc_size = sizeof(*urb)
1906 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1907 urb = calloc(1, alloc_size);
1909 free_iso_urbs(tpriv);
1910 return LIBUSB_ERROR_NO_MEM;
1914 /* populate packet lengths */
1915 for (j = 0, k = packet_offset - urb_packet_offset;
1916 k < packet_offset; k++, j++) {
1917 packet_len = transfer->iso_packet_desc[k].length;
1918 urb->iso_frame_desc[j].length = packet_len;
1921 urb->usercontext = itransfer;
1922 urb->type = USBFS_URB_TYPE_ISO;
1923 /* FIXME: interface for non-ASAP data? */
1924 urb->flags = USBFS_URB_ISO_ASAP;
1925 urb->endpoint = transfer->endpoint;
1926 urb->number_of_packets = urb_packet_offset;
1927 urb->buffer = urb_buffer_orig;
1931 for (i = 0; i < num_urbs; i++) {
1932 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1934 if (errno == ENODEV) {
1935 r = LIBUSB_ERROR_NO_DEVICE;
1937 usbi_err(TRANSFER_CTX(transfer),
1938 "submiturb failed error %d errno=%d", r, errno);
1939 r = LIBUSB_ERROR_IO;
1942 /* if the first URB submission fails, we can simply free up and
1943 * return failure immediately. */
1945 usbi_dbg("first URB failed, easy peasy");
1946 free_iso_urbs(tpriv);
1950 /* if it's not the first URB that failed, the situation is a bit
1951 * tricky. we must discard all previous URBs. there are
1953 * - discarding is asynchronous - discarded urbs will be reaped
1954 * later. the user must not have freed the transfer when the
1955 * discarded URBs are reaped, otherwise libusbx will be using
1957 * - the earlier URBs may have completed successfully and we do
1958 * not want to throw away any data.
1959 * so, in this case we discard all the previous URBs BUT we report
1960 * that the transfer was submitted successfully. then later when
1961 * the final discard completes we can report error to the user.
1963 tpriv->reap_action = SUBMIT_FAILED;
1965 /* The URBs we haven't submitted yet we count as already
1967 tpriv->num_retired = num_urbs - i;
1968 discard_urbs(itransfer, 0, i);
1970 usbi_dbg("reporting successful submission but waiting for %d "
1971 "discards before reporting error", i);
1979 static int submit_control_transfer(struct usbi_transfer *itransfer)
1981 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1982 struct libusb_transfer *transfer =
1983 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1984 struct linux_device_handle_priv *dpriv =
1985 _device_handle_priv(transfer->dev_handle);
1986 struct usbfs_urb *urb;
1990 return LIBUSB_ERROR_BUSY;
1992 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1993 return LIBUSB_ERROR_INVALID_PARAM;
1995 urb = calloc(1, sizeof(struct usbfs_urb));
1997 return LIBUSB_ERROR_NO_MEM;
1999 tpriv->num_urbs = 1;
2000 tpriv->reap_action = NORMAL;
2002 urb->usercontext = itransfer;
2003 urb->type = USBFS_URB_TYPE_CONTROL;
2004 urb->endpoint = transfer->endpoint;
2005 urb->buffer = transfer->buffer;
2006 urb->buffer_length = transfer->length;
2008 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2012 if (errno == ENODEV)
2013 return LIBUSB_ERROR_NO_DEVICE;
2015 usbi_err(TRANSFER_CTX(transfer),
2016 "submiturb failed error %d errno=%d", r, errno);
2017 return LIBUSB_ERROR_IO;
2022 static int op_submit_transfer(struct usbi_transfer *itransfer)
2024 struct libusb_transfer *transfer =
2025 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2027 switch (transfer->type) {
2028 case LIBUSB_TRANSFER_TYPE_CONTROL:
2029 return submit_control_transfer(itransfer);
2030 case LIBUSB_TRANSFER_TYPE_BULK:
2031 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2032 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2033 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2034 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2035 return submit_iso_transfer(itransfer);
2037 usbi_err(TRANSFER_CTX(transfer),
2038 "unknown endpoint type %d", transfer->type);
2039 return LIBUSB_ERROR_INVALID_PARAM;
2043 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2045 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2046 struct libusb_transfer *transfer =
2047 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2049 switch (transfer->type) {
2050 case LIBUSB_TRANSFER_TYPE_BULK:
2051 if (tpriv->reap_action == ERROR)
2053 /* else, fall through */
2054 case LIBUSB_TRANSFER_TYPE_CONTROL:
2055 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2056 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2057 tpriv->reap_action = CANCELLED;
2060 usbi_err(TRANSFER_CTX(transfer),
2061 "unknown endpoint type %d", transfer->type);
2062 return LIBUSB_ERROR_INVALID_PARAM;
2066 return LIBUSB_ERROR_NOT_FOUND;
2068 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2071 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2073 struct libusb_transfer *transfer =
2074 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2075 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2077 /* urbs can be freed also in submit_transfer so lock mutex first */
2078 switch (transfer->type) {
2079 case LIBUSB_TRANSFER_TYPE_CONTROL:
2080 case LIBUSB_TRANSFER_TYPE_BULK:
2081 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2082 usbi_mutex_lock(&itransfer->lock);
2086 usbi_mutex_unlock(&itransfer->lock);
2088 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2089 usbi_mutex_lock(&itransfer->lock);
2090 if (tpriv->iso_urbs)
2091 free_iso_urbs(tpriv);
2092 usbi_mutex_unlock(&itransfer->lock);
2095 usbi_err(TRANSFER_CTX(transfer),
2096 "unknown endpoint type %d", transfer->type);
2100 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2101 struct usbfs_urb *urb)
2103 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2104 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2105 int urb_idx = urb - tpriv->urbs;
2107 usbi_mutex_lock(&itransfer->lock);
2108 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2109 urb_idx + 1, tpriv->num_urbs);
2111 tpriv->num_retired++;
2113 if (tpriv->reap_action != NORMAL) {
2114 /* cancelled, submit_fail, or completed early */
2115 usbi_dbg("abnormal reap: urb status %d", urb->status);
2117 /* even though we're in the process of cancelling, it's possible that
2118 * we may receive some data in these URBs that we don't want to lose.
2120 * 1. while the kernel is cancelling all the packets that make up an
2121 * URB, a few of them might complete. so we get back a successful
2122 * cancellation *and* some data.
2123 * 2. we receive a short URB which marks the early completion condition,
2124 * so we start cancelling the remaining URBs. however, we're too
2125 * slow and another URB completes (or at least completes partially).
2126 * (this can't happen since we always use BULK_CONTINUATION.)
2128 * When this happens, our objectives are not to lose any "surplus" data,
2129 * and also to stick it at the end of the previously-received data
2130 * (closing any holes), so that libusbx reports the total amount of
2131 * transferred data and presents it in a contiguous chunk.
2133 if (urb->actual_length > 0) {
2134 unsigned char *target = transfer->buffer + itransfer->transferred;
2135 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2136 if (urb->buffer != target) {
2137 usbi_dbg("moving surplus data from offset %d to offset %d",
2138 (unsigned char *) urb->buffer - transfer->buffer,
2139 target - transfer->buffer);
2140 memmove(target, urb->buffer, urb->actual_length);
2142 itransfer->transferred += urb->actual_length;
2145 if (tpriv->num_retired == tpriv->num_urbs) {
2146 usbi_dbg("abnormal reap: last URB handled, reporting");
2147 if (tpriv->reap_action != COMPLETED_EARLY &&
2148 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2149 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2155 itransfer->transferred += urb->actual_length;
2157 /* Many of these errors can occur on *any* urb of a multi-urb
2158 * transfer. When they do, we tear down the rest of the transfer.
2160 switch (urb->status) {
2163 case -EREMOTEIO: /* short transfer */
2165 case -ENOENT: /* cancelled */
2170 usbi_dbg("device removed");
2171 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2172 goto cancel_remaining;
2174 usbi_dbg("detected endpoint stall");
2175 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2176 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2177 goto cancel_remaining;
2179 /* overflow can only ever occur in the last urb */
2180 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2181 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2182 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2189 usbi_dbg("low level error %d", urb->status);
2190 tpriv->reap_action = ERROR;
2191 goto cancel_remaining;
2193 usbi_warn(ITRANSFER_CTX(itransfer),
2194 "unrecognised urb status %d", urb->status);
2195 tpriv->reap_action = ERROR;
2196 goto cancel_remaining;
2199 /* if we're the last urb or we got less data than requested then we're
2201 if (urb_idx == tpriv->num_urbs - 1) {
2202 usbi_dbg("last URB in transfer --> complete!");
2204 } else if (urb->actual_length < urb->buffer_length) {
2205 usbi_dbg("short transfer %d/%d --> complete!",
2206 urb->actual_length, urb->buffer_length);
2207 if (tpriv->reap_action == NORMAL)
2208 tpriv->reap_action = COMPLETED_EARLY;
2213 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2214 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2216 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2219 /* cancel remaining urbs and wait for their completion before
2220 * reporting results */
2221 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2224 usbi_mutex_unlock(&itransfer->lock);
2230 usbi_mutex_unlock(&itransfer->lock);
2231 return CANCELLED == tpriv->reap_action ?
2232 usbi_handle_transfer_cancellation(itransfer) :
2233 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2236 static int handle_iso_completion(struct usbi_transfer *itransfer,
2237 struct usbfs_urb *urb)
2239 struct libusb_transfer *transfer =
2240 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2241 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2242 int num_urbs = tpriv->num_urbs;
2245 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2247 usbi_mutex_lock(&itransfer->lock);
2248 for (i = 0; i < num_urbs; i++) {
2249 if (urb == tpriv->iso_urbs[i]) {
2255 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2256 usbi_mutex_unlock(&itransfer->lock);
2257 return LIBUSB_ERROR_NOT_FOUND;
2260 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2263 /* copy isochronous results back in */
2265 for (i = 0; i < urb->number_of_packets; i++) {
2266 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2267 struct libusb_iso_packet_descriptor *lib_desc =
2268 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2269 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2270 switch (urb_desc->status) {
2273 case -ENOENT: /* cancelled */
2278 usbi_dbg("device removed");
2279 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2282 usbi_dbg("detected endpoint stall");
2283 lib_desc->status = LIBUSB_TRANSFER_STALL;
2286 usbi_dbg("overflow error");
2287 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2295 usbi_dbg("low-level USB error %d", urb_desc->status);
2296 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2299 usbi_warn(TRANSFER_CTX(transfer),
2300 "unrecognised urb status %d", urb_desc->status);
2301 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2304 lib_desc->actual_length = urb_desc->actual_length;
2307 tpriv->num_retired++;
2309 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2310 usbi_dbg("CANCEL: urb status %d", urb->status);
2312 if (tpriv->num_retired == num_urbs) {
2313 usbi_dbg("CANCEL: last URB handled, reporting");
2314 free_iso_urbs(tpriv);
2315 if (tpriv->reap_action == CANCELLED) {
2316 usbi_mutex_unlock(&itransfer->lock);
2317 return usbi_handle_transfer_cancellation(itransfer);
2319 usbi_mutex_unlock(&itransfer->lock);
2320 return usbi_handle_transfer_completion(itransfer,
2321 LIBUSB_TRANSFER_ERROR);
2327 switch (urb->status) {
2330 case -ENOENT: /* cancelled */
2334 usbi_dbg("device removed");
2335 status = LIBUSB_TRANSFER_NO_DEVICE;
2338 usbi_warn(TRANSFER_CTX(transfer),
2339 "unrecognised urb status %d", urb->status);
2340 status = LIBUSB_TRANSFER_ERROR;
2344 /* if we're the last urb then we're done */
2345 if (urb_idx == num_urbs) {
2346 usbi_dbg("last URB in transfer --> complete!");
2347 free_iso_urbs(tpriv);
2348 usbi_mutex_unlock(&itransfer->lock);
2349 return usbi_handle_transfer_completion(itransfer, status);
2353 usbi_mutex_unlock(&itransfer->lock);
2357 static int handle_control_completion(struct usbi_transfer *itransfer,
2358 struct usbfs_urb *urb)
2360 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2363 usbi_mutex_lock(&itransfer->lock);
2364 usbi_dbg("handling completion status %d", urb->status);
2366 itransfer->transferred += urb->actual_length;
2368 if (tpriv->reap_action == CANCELLED) {
2369 if (urb->status != 0 && urb->status != -ENOENT)
2370 usbi_warn(ITRANSFER_CTX(itransfer),
2371 "cancel: unrecognised urb status %d", urb->status);
2374 usbi_mutex_unlock(&itransfer->lock);
2375 return usbi_handle_transfer_cancellation(itransfer);
2378 switch (urb->status) {
2380 status = LIBUSB_TRANSFER_COMPLETED;
2382 case -ENOENT: /* cancelled */
2383 status = LIBUSB_TRANSFER_CANCELLED;
2387 usbi_dbg("device removed");
2388 status = LIBUSB_TRANSFER_NO_DEVICE;
2391 usbi_dbg("unsupported control request");
2392 status = LIBUSB_TRANSFER_STALL;
2395 usbi_dbg("control overflow error");
2396 status = LIBUSB_TRANSFER_OVERFLOW;
2403 usbi_dbg("low-level bus error occurred");
2404 status = LIBUSB_TRANSFER_ERROR;
2407 usbi_warn(ITRANSFER_CTX(itransfer),
2408 "unrecognised urb status %d", urb->status);
2409 status = LIBUSB_TRANSFER_ERROR;
2415 usbi_mutex_unlock(&itransfer->lock);
2416 return usbi_handle_transfer_completion(itransfer, status);
2419 static int reap_for_handle(struct libusb_device_handle *handle)
2421 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2423 struct usbfs_urb *urb;
2424 struct usbi_transfer *itransfer;
2425 struct libusb_transfer *transfer;
2427 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2428 if (r == -1 && errno == EAGAIN)
2431 if (errno == ENODEV)
2432 return LIBUSB_ERROR_NO_DEVICE;
2434 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2436 return LIBUSB_ERROR_IO;
2439 itransfer = urb->usercontext;
2440 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2442 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2443 urb->actual_length);
2445 switch (transfer->type) {
2446 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2447 return handle_iso_completion(itransfer, urb);
2448 case LIBUSB_TRANSFER_TYPE_BULK:
2449 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2450 return handle_bulk_completion(itransfer, urb);
2451 case LIBUSB_TRANSFER_TYPE_CONTROL:
2452 return handle_control_completion(itransfer, urb);
2454 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2456 return LIBUSB_ERROR_OTHER;
2460 static int op_handle_events(struct libusb_context *ctx,
2461 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2466 usbi_mutex_lock(&ctx->open_devs_lock);
2467 for (i = 0; i < nfds && num_ready > 0; i++) {
2468 struct pollfd *pollfd = &fds[i];
2469 struct libusb_device_handle *handle;
2470 struct linux_device_handle_priv *hpriv = NULL;
2472 if (!pollfd->revents)
2476 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2477 hpriv = _device_handle_priv(handle);
2478 if (hpriv->fd == pollfd->fd)
2482 if (pollfd->revents & POLLERR) {
2483 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2484 usbi_handle_disconnect(handle);
2489 r = reap_for_handle(handle);
2491 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2499 usbi_mutex_unlock(&ctx->open_devs_lock);
2503 static int op_clock_gettime(int clk_id, struct timespec *tp)
2506 case USBI_CLOCK_MONOTONIC:
2507 return clock_gettime(monotonic_clkid, tp);
2508 case USBI_CLOCK_REALTIME:
2509 return clock_gettime(CLOCK_REALTIME, tp);
2511 return LIBUSB_ERROR_INVALID_PARAM;
2515 #ifdef USBI_TIMERFD_AVAILABLE
2516 static clockid_t op_get_timerfd_clockid(void)
2518 return monotonic_clkid;
2523 const struct usbi_os_backend linux_usbfs_backend = {
2524 .name = "Linux usbfs",
2525 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2528 .get_device_list = NULL,
2529 .hotplug_poll = op_hotplug_poll,
2530 .get_device_descriptor = op_get_device_descriptor,
2531 .get_active_config_descriptor = op_get_active_config_descriptor,
2532 .get_config_descriptor = op_get_config_descriptor,
2533 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2537 .get_configuration = op_get_configuration,
2538 .set_configuration = op_set_configuration,
2539 .claim_interface = op_claim_interface,
2540 .release_interface = op_release_interface,
2542 .set_interface_altsetting = op_set_interface,
2543 .clear_halt = op_clear_halt,
2544 .reset_device = op_reset_device,
2546 .kernel_driver_active = op_kernel_driver_active,
2547 .detach_kernel_driver = op_detach_kernel_driver,
2548 .attach_kernel_driver = op_attach_kernel_driver,
2550 .destroy_device = op_destroy_device,
2552 .submit_transfer = op_submit_transfer,
2553 .cancel_transfer = op_cancel_transfer,
2554 .clear_transfer_priv = op_clear_transfer_priv,
2556 .handle_events = op_handle_events,
2558 .clock_gettime = op_clock_gettime,
2560 #ifdef USBI_TIMERFD_AVAILABLE
2561 .get_timerfd_clockid = op_get_timerfd_clockid,
2564 .device_priv_size = sizeof(struct linux_device_priv),
2565 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2566 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2567 .add_iso_packet_size = 0,