1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/utsname.h>
42 #include "linux_usbfs.h"
45 * opening a usbfs node causes the device to be resumed, so we attempt to
46 * avoid this during enumeration.
48 * sysfs allows us to read the kernel's in-memory copies of device descriptors
49 * and so forth, avoiding the need to open the device:
50 * - The binary "descriptors" file contains all config descriptors since
51 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
52 * - The binary "descriptors" file was added in 2.6.23, commit
53 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
54 * active config descriptors
55 * - The "busnum" file was added in 2.6.22, commit
56 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
57 * - The "devnum" file has been present since pre-2.6.18
58 * - the "bConfigurationValue" file has been present since pre-2.6.18
60 * If we have bConfigurationValue, busnum, and devnum, then we can determine
61 * the active configuration without having to open the usbfs node in RDWR mode.
62 * The busnum file is important as that is the only way we can relate sysfs
63 * devices to usbfs nodes.
65 * If we also have all descriptors, we can obtain the device descriptor and
66 * configuration without touching usbfs at all.
69 /* endianness for multi-byte fields:
71 * Descriptors exposed by usbfs have the multi-byte fields in the device
72 * descriptor as host endian. Multi-byte fields in the other descriptors are
73 * bus-endian. The kernel documentation says otherwise, but it is wrong.
75 * In sysfs all descriptors are bus-endian.
78 static const char *usbfs_path = NULL;
80 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
81 static int usbdev_names = 0;
83 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
84 * allows us to mark URBs as being part of a specific logical transfer when
85 * we submit them to the kernel. then, on any error except a cancellation, all
86 * URBs within that transfer will be cancelled and no more URBs will be
87 * accepted for the transfer, meaning that no more data can creep in.
89 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
90 * (in either direction) except the first.
91 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
92 * last; it means that the kernel should treat a short reply as an error.
93 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
94 * transfers can't be short unless there's already some sort of error), and
95 * setting this flag is disallowed (a kernel with USB debugging enabled will
98 static int supports_flag_bulk_continuation = -1;
100 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
101 * allows us to mark URBs that should be followed by a zero length data
102 * packet, which can be required by device- or class-specific protocols.
104 static int supports_flag_zero_packet = -1;
106 /* clock ID for monotonic clock, as not all clock sources are available on all
107 * systems. appropriate choice made at initialization time. */
108 static clockid_t monotonic_clkid = -1;
110 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
111 * to sysfs, so we can relate devices. This also implies that we can read
112 * the active configuration through bConfigurationValue */
113 static int sysfs_can_relate_devices = -1;
115 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
116 * config descriptors (rather then just the active config) to the sysfs
117 * descriptors file, so from then on we can use them. */
118 static int sysfs_has_descriptors = -1;
120 /* how many times have we initted (and not exited) ? */
121 static int init_count = 0;
123 /* Serialize hotplug start/stop */
124 usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
125 /* Serialize scan-devices, event-thread, and poll */
126 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
128 static int linux_start_event_monitor(void);
129 static int linux_stop_event_monitor(void);
130 static int linux_scan_devices(struct libusb_context *ctx);
131 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
132 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
134 #if !defined(USE_UDEV)
135 static int linux_default_scan_devices (struct libusb_context *ctx);
138 struct linux_device_priv {
140 unsigned char *descriptors;
142 int active_config; /* cache val for !sysfs_can_relate_devices */
145 struct linux_device_handle_priv {
152 /* submission failed after the first URB, so await cancellation/completion
153 * of all the others */
156 /* cancelled by user or timeout */
159 /* completed multi-URB transfer in non-final URB */
162 /* one or more urbs encountered a low-level error */
166 struct linux_transfer_priv {
168 struct usbfs_urb *urbs;
169 struct usbfs_urb **iso_urbs;
172 enum reap_action reap_action;
175 enum libusb_transfer_status reap_status;
177 /* next iso packet in user-supplied transfer to be populated */
178 int iso_packet_offset;
181 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
183 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 */
199 if (errno == ENOENT) {
201 usbi_err(ctx, "File doesn't exist, wait %d ms and try again\n", delay/1000);
203 /* Wait 10ms for USB device path creation.*/
206 fd = open(path, mode);
208 return fd; /* Success */
212 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
213 path, strerror(errno));
214 if (errno == EACCES && mode == O_RDWR)
215 usbi_err(ctx, "libusb requires write access to USB "
220 return LIBUSB_ERROR_ACCESS;
222 return LIBUSB_ERROR_NO_DEVICE;
223 return LIBUSB_ERROR_IO;
226 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
228 return (struct linux_device_priv *) dev->os_priv;
231 static struct linux_device_handle_priv *_device_handle_priv(
232 struct libusb_device_handle *handle)
234 return (struct linux_device_handle_priv *) handle->os_priv;
237 /* check dirent for a /dev/usbdev%d.%d name
238 * optionally return bus/device on success */
239 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
243 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
246 usbi_dbg("found: %s", entry->d_name);
254 static int check_usb_vfs(const char *dirname)
257 struct dirent *entry;
260 dir = opendir(dirname);
264 while ((entry = readdir(dir)) != NULL) {
265 if (entry->d_name[0] == '.')
268 /* We assume if we find any files that it must be the right place */
277 static const char *find_usbfs_path(void)
279 const char *path = "/dev/bus/usb";
280 const char *ret = NULL;
282 if (check_usb_vfs(path)) {
285 path = "/proc/bus/usb";
286 if (check_usb_vfs(path))
290 /* look for /dev/usbdev*.* if the normal places fail */
292 struct dirent *entry;
298 while ((entry = readdir(dir)) != NULL) {
299 if (_is_usbdev_entry(entry, NULL, NULL)) {
300 /* found one; that's enough */
311 usbi_dbg("found usbfs at %s", ret);
316 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
317 * seem to lack it). fall back to REALTIME if we have to. */
318 static clockid_t find_monotonic_clock(void)
320 #ifdef CLOCK_MONOTONIC
324 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
325 * because it's not available through timerfd */
326 r = clock_gettime(CLOCK_MONOTONIC, &ts);
328 return CLOCK_MONOTONIC;
329 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
332 return CLOCK_REALTIME;
335 static int kernel_version_ge(int major, int minor, int sublevel)
338 int atoms, kmajor, kminor, ksublevel;
342 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
351 /* kmajor == major */
353 return 0 == minor && 0 == sublevel;
359 /* kminor == minor */
361 return 0 == sublevel;
363 return ksublevel >= sublevel;
366 static int op_init(struct libusb_context *ctx)
371 usbfs_path = find_usbfs_path();
373 usbi_err(ctx, "could not find usbfs");
374 return LIBUSB_ERROR_OTHER;
377 if (monotonic_clkid == -1)
378 monotonic_clkid = find_monotonic_clock();
380 if (supports_flag_bulk_continuation == -1) {
381 /* bulk continuation URB flag available from Linux 2.6.32 */
382 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
383 if (supports_flag_bulk_continuation == -1) {
384 usbi_err(ctx, "error checking for bulk continuation support");
385 return LIBUSB_ERROR_OTHER;
389 if (supports_flag_bulk_continuation)
390 usbi_dbg("bulk continuation flag supported");
392 if (-1 == supports_flag_zero_packet) {
393 /* zero length packet URB flag fixed since Linux 2.6.31 */
394 supports_flag_zero_packet = kernel_version_ge(2,6,31);
395 if (-1 == supports_flag_zero_packet) {
396 usbi_err(ctx, "error checking for zero length packet support");
397 return LIBUSB_ERROR_OTHER;
401 if (supports_flag_zero_packet)
402 usbi_dbg("zero length packet flag supported");
404 if (-1 == sysfs_has_descriptors) {
405 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
406 sysfs_has_descriptors = kernel_version_ge(2,6,26);
407 if (-1 == sysfs_has_descriptors) {
408 usbi_err(ctx, "error checking for sysfs descriptors");
409 return LIBUSB_ERROR_OTHER;
413 if (-1 == sysfs_can_relate_devices) {
414 /* sysfs has busnum since Linux 2.6.22 */
415 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
416 if (-1 == sysfs_can_relate_devices) {
417 usbi_err(ctx, "error checking for sysfs busnum");
418 return LIBUSB_ERROR_OTHER;
422 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
423 r = stat(SYSFS_DEVICE_PATH, &statbuf);
424 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
425 usbi_warn(ctx, "sysfs not mounted");
426 sysfs_can_relate_devices = 0;
427 sysfs_has_descriptors = 0;
431 if (sysfs_can_relate_devices)
432 usbi_dbg("sysfs can relate devices");
434 if (sysfs_has_descriptors)
435 usbi_dbg("sysfs has complete descriptors");
437 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
439 if (init_count == 0) {
440 /* start up hotplug event handler */
441 r = linux_start_event_monitor();
443 if (r == LIBUSB_SUCCESS) {
444 r = linux_scan_devices(ctx);
445 if (r == LIBUSB_SUCCESS)
447 else if (init_count == 0)
448 linux_stop_event_monitor();
450 usbi_err(ctx, "error starting hotplug event monitor");
451 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
456 static void op_exit(void)
458 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
459 assert(init_count != 0);
461 /* tear down event handler */
462 (void)linux_stop_event_monitor();
464 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
467 static int linux_start_event_monitor(void)
469 #if defined(USE_UDEV)
470 return linux_udev_start_event_monitor();
472 return linux_netlink_start_event_monitor();
476 static int linux_stop_event_monitor(void)
478 #if defined(USE_UDEV)
479 return linux_udev_stop_event_monitor();
481 return linux_netlink_stop_event_monitor();
485 static int linux_scan_devices(struct libusb_context *ctx)
489 usbi_mutex_static_lock(&linux_hotplug_lock);
491 #if defined(USE_UDEV)
492 ret = linux_udev_scan_devices(ctx);
494 ret = linux_default_scan_devices(ctx);
497 usbi_mutex_static_unlock(&linux_hotplug_lock);
502 static void op_hotplug_poll(void)
504 #if defined(USE_UDEV)
505 linux_udev_hotplug_poll();
507 linux_netlink_hotplug_poll();
511 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
513 struct linux_device_priv *priv = _device_priv(dev);
514 char filename[PATH_MAX];
517 snprintf(filename, PATH_MAX, "%s/%s/%s",
518 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
519 fd = open(filename, O_RDONLY);
521 usbi_err(DEVICE_CTX(dev),
522 "open %s failed ret=%d errno=%d", filename, fd, errno);
523 return LIBUSB_ERROR_IO;
529 /* Note only suitable for attributes which always read >= 0, < 0 is error */
530 static int __read_sysfs_attr(struct libusb_context *ctx,
531 const char *devname, const char *attr)
533 char filename[PATH_MAX];
537 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
539 f = fopen(filename, "r");
541 if (errno == ENOENT) {
542 /* File doesn't exist. Assume the device has been
543 disconnected (see trac ticket #70). */
544 return LIBUSB_ERROR_NO_DEVICE;
546 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
547 return LIBUSB_ERROR_IO;
550 r = fscanf(f, "%d", &value);
553 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
554 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
557 usbi_err(ctx, "%s contains a negative value", filename);
558 return LIBUSB_ERROR_IO;
564 static int op_get_device_descriptor(struct libusb_device *dev,
565 unsigned char *buffer, int *host_endian)
567 struct linux_device_priv *priv = _device_priv(dev);
569 *host_endian = sysfs_has_descriptors ? 0 : 1;
570 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
575 /* read the bConfigurationValue for a device */
576 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
579 char tmp[5] = {0, 0, 0, 0, 0};
584 fd = _open_sysfs_attr(dev, "bConfigurationValue");
588 r = read(fd, tmp, sizeof(tmp));
591 usbi_err(DEVICE_CTX(dev),
592 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
593 return LIBUSB_ERROR_IO;
595 usbi_dbg("device unconfigured");
600 if (tmp[sizeof(tmp) - 1] != 0) {
601 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
602 return LIBUSB_ERROR_IO;
603 } else if (tmp[0] == 0) {
604 usbi_err(DEVICE_CTX(dev), "no configuration value?");
605 return LIBUSB_ERROR_IO;
608 num = strtol(tmp, &endptr, 10);
610 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
611 return LIBUSB_ERROR_IO;
618 int linux_get_device_address (struct libusb_context *ctx, int detached,
619 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
620 const char *sys_name)
624 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
625 /* can't use sysfs to read the bus and device number if the
626 * device has been detached */
627 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
628 if (NULL == dev_node) {
629 return LIBUSB_ERROR_OTHER;
632 /* will this work with all supported kernel versions? */
633 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
634 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
635 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
636 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
639 return LIBUSB_SUCCESS;
642 usbi_dbg("scan %s", sys_name);
644 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
647 if (sysfs_attr > 255)
648 return LIBUSB_ERROR_INVALID_PARAM;
649 *busnum = (uint8_t) sysfs_attr;
651 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
654 if (sysfs_attr > 255)
655 return LIBUSB_ERROR_INVALID_PARAM;
657 *devaddr = (uint8_t) sysfs_attr;
659 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
661 return LIBUSB_SUCCESS;
664 /* Return offset of the next descriptor with the given type */
665 static int seek_to_next_descriptor(struct libusb_context *ctx,
666 uint8_t descriptor_type, unsigned char *buffer, int size)
668 struct usb_descriptor_header header;
671 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
673 return LIBUSB_ERROR_NOT_FOUND;
676 usbi_err(ctx, "short descriptor read %d/2", size);
677 return LIBUSB_ERROR_IO;
679 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
681 if (i && header.bDescriptorType == descriptor_type)
684 usbi_err(ctx, "bLength overflow by %d bytes", -size);
685 return LIBUSB_ERROR_IO;
688 /* Return offset to next config */
689 static int seek_to_next_config(struct libusb_context *ctx,
690 unsigned char *buffer, int size)
692 struct libusb_config_descriptor config;
695 return LIBUSB_ERROR_NOT_FOUND;
697 if (size < LIBUSB_DT_CONFIG_SIZE) {
698 usbi_err(ctx, "short descriptor read %d/%d",
699 size, LIBUSB_DT_CONFIG_SIZE);
700 return LIBUSB_ERROR_IO;
703 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
704 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
705 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
706 config.bDescriptorType);
707 return LIBUSB_ERROR_IO;
711 * In usbfs the config descriptors are config.wTotalLength bytes apart,
712 * with any short reads from the device appearing as holes in the file.
714 * In sysfs wTotalLength is ignored, instead the kernel returns a
715 * config descriptor with verified bLength fields, with descriptors
716 * with an invalid bLength removed.
718 if (sysfs_has_descriptors) {
719 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
721 if (next == LIBUSB_ERROR_NOT_FOUND)
726 if (next != config.wTotalLength)
727 usbi_warn(ctx, "config length mismatch wTotalLength "
728 "%d real %d", config.wTotalLength, next);
731 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
732 usbi_err(ctx, "invalid wTotalLength %d",
733 config.wTotalLength);
734 return LIBUSB_ERROR_IO;
735 } else if (config.wTotalLength > size) {
736 usbi_warn(ctx, "short descriptor read %d/%d",
737 size, config.wTotalLength);
740 return config.wTotalLength;
744 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
745 uint8_t value, unsigned char **buffer, int *host_endian)
747 struct libusb_context *ctx = DEVICE_CTX(dev);
748 struct linux_device_priv *priv = _device_priv(dev);
749 unsigned char *descriptors = priv->descriptors;
750 int size = priv->descriptors_len;
751 struct libusb_config_descriptor *config;
754 /* Unlike the device desc. config descs. are always in raw format */
757 /* Skip device header */
758 descriptors += DEVICE_DESC_LENGTH;
759 size -= DEVICE_DESC_LENGTH;
761 /* Seek till the config is found, or till "EOF" */
763 int next = seek_to_next_config(ctx, descriptors, size);
766 config = (struct libusb_config_descriptor *)descriptors;
767 if (config->bConfigurationValue == value) {
768 *buffer = descriptors;
776 static int op_get_active_config_descriptor(struct libusb_device *dev,
777 unsigned char *buffer, size_t len, int *host_endian)
780 unsigned char *config_desc;
782 if (sysfs_can_relate_devices) {
783 r = sysfs_get_active_config(dev, &config);
787 /* Use cached bConfigurationValue */
788 struct linux_device_priv *priv = _device_priv(dev);
789 config = priv->active_config;
792 return LIBUSB_ERROR_NOT_FOUND;
794 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
800 memcpy(buffer, config_desc, len);
804 static int op_get_config_descriptor(struct libusb_device *dev,
805 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
807 struct linux_device_priv *priv = _device_priv(dev);
808 unsigned char *descriptors = priv->descriptors;
809 int i, r, size = priv->descriptors_len;
811 /* Unlike the device desc. config descs. are always in raw format */
814 /* Skip device header */
815 descriptors += DEVICE_DESC_LENGTH;
816 size -= DEVICE_DESC_LENGTH;
818 /* Seek till the config is found, or till "EOF" */
820 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
823 if (i == config_index)
830 memcpy(buffer, descriptors, len);
834 /* send a control message to retrieve active configuration */
835 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
837 unsigned char active_config = 0;
840 struct usbfs_ctrltransfer ctrl = {
841 .bmRequestType = LIBUSB_ENDPOINT_IN,
842 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
847 .data = &active_config
850 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
853 return LIBUSB_ERROR_NO_DEVICE;
855 /* we hit this error path frequently with buggy devices :( */
856 usbi_warn(DEVICE_CTX(dev),
857 "get_configuration failed ret=%d errno=%d", r, errno);
858 return LIBUSB_ERROR_IO;
861 return active_config;
864 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
865 uint8_t devaddr, const char *sysfs_dir)
867 struct linux_device_priv *priv = _device_priv(dev);
868 struct libusb_context *ctx = DEVICE_CTX(dev);
869 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
873 dev->bus_number = busnum;
874 dev->device_address = devaddr;
877 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
878 if (!priv->sysfs_dir)
879 return LIBUSB_ERROR_NO_MEM;
880 strcpy(priv->sysfs_dir, sysfs_dir);
882 /* Note speed can contain 1.5, in this case __read_sysfs_attr
883 will stop parsing at the '.' and return 1 */
884 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
887 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
888 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
889 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
890 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
892 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
897 /* cache descriptors in memory */
898 if (sysfs_has_descriptors)
899 fd = _open_sysfs_attr(dev, "descriptors");
901 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
906 descriptors_size *= 2;
907 priv->descriptors = usbi_reallocf(priv->descriptors,
909 if (!priv->descriptors) {
911 return LIBUSB_ERROR_NO_MEM;
913 /* usbfs has holes in the file */
914 if (!sysfs_has_descriptors) {
915 memset(priv->descriptors + priv->descriptors_len,
916 0, descriptors_size - priv->descriptors_len);
918 r = read(fd, priv->descriptors + priv->descriptors_len,
919 descriptors_size - priv->descriptors_len);
921 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
924 return LIBUSB_ERROR_IO;
926 priv->descriptors_len += r;
927 } while (priv->descriptors_len == descriptors_size);
931 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
932 usbi_err(ctx, "short descriptor read (%d)",
933 priv->descriptors_len);
934 return LIBUSB_ERROR_IO;
937 if (sysfs_can_relate_devices)
938 return LIBUSB_SUCCESS;
940 /* cache active config */
941 fd = _get_usbfs_fd(dev, O_RDWR, 1);
943 /* cannot send a control message to determine the active
944 * config. just assume the first one is active. */
945 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
946 "active configuration descriptor");
947 if (priv->descriptors_len >=
948 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
949 struct libusb_config_descriptor config;
950 usbi_parse_descriptor(
951 priv->descriptors + DEVICE_DESC_LENGTH,
952 "bbwbbbbb", &config, 0);
953 priv->active_config = config.bConfigurationValue;
955 priv->active_config = -1; /* No config dt */
957 return LIBUSB_SUCCESS;
960 r = usbfs_get_active_config(dev, fd);
962 priv->active_config = r;
965 /* some buggy devices have a configuration 0, but we're
966 * reaching into the corner of a corner case here, so let's
967 * not support buggy devices in these circumstances.
968 * stick to the specs: a configuration value of 0 means
970 usbi_dbg("active cfg 0? assuming unconfigured device");
971 priv->active_config = -1;
973 } else if (r == LIBUSB_ERROR_IO) {
974 /* buggy devices sometimes fail to report their active config.
975 * assume unconfigured and continue the probing */
976 usbi_warn(ctx, "couldn't query active configuration, assuming"
978 priv->active_config = -1;
980 } /* else r < 0, just return the error code */
986 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
988 struct libusb_context *ctx = DEVICE_CTX(dev);
989 struct libusb_device *it;
990 char *parent_sysfs_dir, *tmp;
991 int ret, add_parent = 1;
993 /* XXX -- can we figure out the topology when using usbfs? */
994 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
995 /* either using usbfs or finding the parent of a root hub */
996 return LIBUSB_SUCCESS;
999 parent_sysfs_dir = strdup(sysfs_dir);
1000 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1001 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1002 dev->port_number = atoi(tmp + 1);
1005 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1007 free (parent_sysfs_dir);
1008 return LIBUSB_SUCCESS;
1011 /* is the parent a root hub? */
1012 if (NULL == strchr(parent_sysfs_dir, '-')) {
1013 tmp = parent_sysfs_dir;
1014 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1017 return LIBUSB_ERROR_NO_MEM;
1022 /* find the parent in the context */
1023 usbi_mutex_lock(&ctx->usb_devs_lock);
1024 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1025 struct linux_device_priv *priv = _device_priv(it);
1026 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1027 dev->parent_dev = libusb_ref_device(it);
1031 usbi_mutex_unlock(&ctx->usb_devs_lock);
1033 if (!dev->parent_dev && add_parent) {
1034 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1036 sysfs_scan_device(ctx, parent_sysfs_dir);
1041 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1042 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1044 free (parent_sysfs_dir);
1046 return LIBUSB_SUCCESS;
1049 int linux_enumerate_device(struct libusb_context *ctx,
1050 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1052 unsigned long session_id;
1053 struct libusb_device *dev;
1056 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1057 * will be reused. instead we should add a simple sysfs attribute with
1059 session_id = busnum << 8 | devaddr;
1060 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1063 dev = usbi_get_device_by_session_id(ctx, session_id);
1065 /* device already exists in the context */
1066 usbi_dbg("session_id %ld already exists", session_id);
1067 libusb_unref_device(dev);
1068 return LIBUSB_SUCCESS;
1071 usbi_dbg("allocating new device for %d/%d (session %ld)",
1072 busnum, devaddr, session_id);
1073 dev = usbi_alloc_device(ctx, session_id);
1075 return LIBUSB_ERROR_NO_MEM;
1077 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1080 r = usbi_sanitize_device(dev);
1084 r = linux_get_parent_info(dev, sysfs_dir);
1089 libusb_unref_device(dev);
1091 usbi_connect_device(dev);
1096 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1098 struct libusb_context *ctx;
1100 usbi_mutex_static_lock(&active_contexts_lock);
1101 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1102 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1104 usbi_mutex_static_unlock(&active_contexts_lock);
1107 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1109 struct libusb_context *ctx;
1110 struct libusb_device *dev;
1111 unsigned long session_id = busnum << 8 | devaddr;
1113 usbi_mutex_static_lock(&active_contexts_lock);
1114 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1115 dev = usbi_get_device_by_session_id (ctx, session_id);
1117 usbi_disconnect_device (dev);
1118 libusb_unref_device(dev);
1120 usbi_dbg("device not found for session %x", session_id);
1123 usbi_mutex_static_unlock(&active_contexts_lock);
1126 #if !defined(USE_UDEV)
1127 /* open a bus directory and adds all discovered devices to the context */
1128 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1131 char dirpath[PATH_MAX];
1132 struct dirent *entry;
1133 int r = LIBUSB_ERROR_IO;
1135 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1136 usbi_dbg("%s", dirpath);
1137 dir = opendir(dirpath);
1139 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1140 /* FIXME: should handle valid race conditions like hub unplugged
1141 * during directory iteration - this is not an error */
1145 while ((entry = readdir(dir))) {
1148 if (entry->d_name[0] == '.')
1151 devaddr = atoi(entry->d_name);
1153 usbi_dbg("unknown dir entry %s", entry->d_name);
1157 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1158 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1169 static int usbfs_get_device_list(struct libusb_context *ctx)
1171 struct dirent *entry;
1172 DIR *buses = opendir(usbfs_path);
1176 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1177 return LIBUSB_ERROR_IO;
1180 while ((entry = readdir(buses))) {
1183 if (entry->d_name[0] == '.')
1188 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1191 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1193 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1197 busnum = atoi(entry->d_name);
1199 usbi_dbg("unknown dir entry %s", entry->d_name);
1203 r = usbfs_scan_busdir(ctx, busnum);
1215 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1217 uint8_t busnum, devaddr;
1220 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1221 if (LIBUSB_SUCCESS != ret) {
1225 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1229 #if !defined(USE_UDEV)
1230 static int sysfs_get_device_list(struct libusb_context *ctx)
1232 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1233 struct dirent *entry;
1234 int r = LIBUSB_ERROR_IO;
1237 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1241 while ((entry = readdir(devices))) {
1242 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1243 || strchr(entry->d_name, ':'))
1246 if (sysfs_scan_device(ctx, entry->d_name)) {
1247 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1258 static int linux_default_scan_devices (struct libusb_context *ctx)
1260 /* we can retrieve device list and descriptors from sysfs or usbfs.
1261 * sysfs is preferable, because if we use usbfs we end up resuming
1262 * any autosuspended USB devices. however, sysfs is not available
1263 * everywhere, so we need a usbfs fallback too.
1265 * as described in the "sysfs vs usbfs" comment at the top of this
1266 * file, sometimes we have sysfs but not enough information to
1267 * relate sysfs devices to usbfs nodes. op_init() determines the
1268 * adequacy of sysfs and sets sysfs_can_relate_devices.
1270 if (sysfs_can_relate_devices != 0)
1271 return sysfs_get_device_list(ctx);
1273 return usbfs_get_device_list(ctx);
1277 static int op_open(struct libusb_device_handle *handle)
1279 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1282 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1283 if (hpriv->fd < 0) {
1284 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1285 /* device will still be marked as attached if hotplug monitor thread
1286 * hasn't processed remove event yet */
1287 usbi_mutex_static_lock(&linux_hotplug_lock);
1288 if (handle->dev->attached) {
1289 usbi_dbg("open failed with no device, but device still attached");
1290 linux_device_disconnected(handle->dev->bus_number,
1291 handle->dev->device_address, NULL);
1293 usbi_mutex_static_unlock(&linux_hotplug_lock);
1298 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1300 if (errno == ENOTTY)
1301 usbi_dbg("getcap not available");
1303 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1305 if (supports_flag_zero_packet)
1306 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1307 if (supports_flag_bulk_continuation)
1308 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1311 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1314 static void op_close(struct libusb_device_handle *dev_handle)
1316 int fd = _device_handle_priv(dev_handle)->fd;
1317 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1321 static int op_get_configuration(struct libusb_device_handle *handle,
1326 if (sysfs_can_relate_devices) {
1327 r = sysfs_get_active_config(handle->dev, config);
1329 r = usbfs_get_active_config(handle->dev,
1330 _device_handle_priv(handle)->fd);
1335 if (*config == -1) {
1336 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1343 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1345 struct linux_device_priv *priv = _device_priv(handle->dev);
1346 int fd = _device_handle_priv(handle)->fd;
1347 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1349 if (errno == EINVAL)
1350 return LIBUSB_ERROR_NOT_FOUND;
1351 else if (errno == EBUSY)
1352 return LIBUSB_ERROR_BUSY;
1353 else if (errno == ENODEV)
1354 return LIBUSB_ERROR_NO_DEVICE;
1356 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1357 return LIBUSB_ERROR_OTHER;
1360 /* update our cached active config descriptor */
1361 priv->active_config = config;
1363 return LIBUSB_SUCCESS;
1366 static int claim_interface(struct libusb_device_handle *handle, int iface)
1368 int fd = _device_handle_priv(handle)->fd;
1369 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1371 if (errno == ENOENT)
1372 return LIBUSB_ERROR_NOT_FOUND;
1373 else if (errno == EBUSY)
1374 return LIBUSB_ERROR_BUSY;
1375 else if (errno == ENODEV)
1376 return LIBUSB_ERROR_NO_DEVICE;
1378 usbi_err(HANDLE_CTX(handle),
1379 "claim interface failed, error %d errno %d", r, errno);
1380 return LIBUSB_ERROR_OTHER;
1385 static int release_interface(struct libusb_device_handle *handle, int iface)
1387 int fd = _device_handle_priv(handle)->fd;
1388 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1390 if (errno == ENODEV)
1391 return LIBUSB_ERROR_NO_DEVICE;
1393 usbi_err(HANDLE_CTX(handle),
1394 "release interface failed, error %d errno %d", r, errno);
1395 return LIBUSB_ERROR_OTHER;
1400 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1403 int fd = _device_handle_priv(handle)->fd;
1404 struct usbfs_setinterface setintf;
1407 setintf.interface = iface;
1408 setintf.altsetting = altsetting;
1409 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1411 if (errno == EINVAL)
1412 return LIBUSB_ERROR_NOT_FOUND;
1413 else if (errno == ENODEV)
1414 return LIBUSB_ERROR_NO_DEVICE;
1416 usbi_err(HANDLE_CTX(handle),
1417 "setintf failed error %d errno %d", r, errno);
1418 return LIBUSB_ERROR_OTHER;
1424 static int op_clear_halt(struct libusb_device_handle *handle,
1425 unsigned char endpoint)
1427 int fd = _device_handle_priv(handle)->fd;
1428 unsigned int _endpoint = endpoint;
1429 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1431 if (errno == ENOENT)
1432 return LIBUSB_ERROR_NOT_FOUND;
1433 else if (errno == ENODEV)
1434 return LIBUSB_ERROR_NO_DEVICE;
1436 usbi_err(HANDLE_CTX(handle),
1437 "clear_halt failed error %d errno %d", r, errno);
1438 return LIBUSB_ERROR_OTHER;
1444 static int op_reset_device(struct libusb_device_handle *handle)
1446 int fd = _device_handle_priv(handle)->fd;
1449 /* Doing a device reset will cause the usbfs driver to get unbound
1450 from any interfaces it is bound to. By voluntarily unbinding
1451 the usbfs driver ourself, we stop the kernel from rebinding
1452 the interface after reset (which would end up with the interface
1453 getting bound to the in kernel driver if any). */
1454 for (i = 0; i < USB_MAXINTERFACES; i++) {
1455 if (handle->claimed_interfaces & (1L << i)) {
1456 release_interface(handle, i);
1460 usbi_mutex_lock(&handle->lock);
1461 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1463 if (errno == ENODEV) {
1464 ret = LIBUSB_ERROR_NOT_FOUND;
1468 usbi_err(HANDLE_CTX(handle),
1469 "reset failed error %d errno %d", r, errno);
1470 ret = LIBUSB_ERROR_OTHER;
1474 /* And re-claim any interfaces which were claimed before the reset */
1475 for (i = 0; i < USB_MAXINTERFACES; i++) {
1476 if (handle->claimed_interfaces & (1L << i)) {
1478 * A driver may have completed modprobing during
1479 * IOCTL_USBFS_RESET, and bound itself as soon as
1480 * IOCTL_USBFS_RESET released the device lock
1482 r = detach_kernel_driver_and_claim(handle, i);
1484 usbi_warn(HANDLE_CTX(handle),
1485 "failed to re-claim interface %d after reset: %s",
1486 i, libusb_error_name(r));
1487 handle->claimed_interfaces &= ~(1L << i);
1488 ret = LIBUSB_ERROR_NOT_FOUND;
1493 usbi_mutex_unlock(&handle->lock);
1497 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1498 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1500 int r, fd = _device_handle_priv(handle)->fd;
1501 struct usbfs_streams *streams;
1503 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1504 return LIBUSB_ERROR_INVALID_PARAM;
1506 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1508 return LIBUSB_ERROR_NO_MEM;
1510 streams->num_streams = num_streams;
1511 streams->num_eps = num_endpoints;
1512 memcpy(streams->eps, endpoints, num_endpoints);
1514 r = ioctl(fd, req, streams);
1519 if (errno == ENOTTY)
1520 return LIBUSB_ERROR_NOT_SUPPORTED;
1521 else if (errno == EINVAL)
1522 return LIBUSB_ERROR_INVALID_PARAM;
1523 else if (errno == ENODEV)
1524 return LIBUSB_ERROR_NO_DEVICE;
1526 usbi_err(HANDLE_CTX(handle),
1527 "streams-ioctl failed error %d errno %d", r, errno);
1528 return LIBUSB_ERROR_OTHER;
1533 static int op_alloc_streams(struct libusb_device_handle *handle,
1534 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1536 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1537 num_streams, endpoints, num_endpoints);
1540 static int op_free_streams(struct libusb_device_handle *handle,
1541 unsigned char *endpoints, int num_endpoints)
1543 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1544 endpoints, num_endpoints);
1547 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1550 int fd = _device_handle_priv(handle)->fd;
1551 struct usbfs_getdriver getdrv;
1554 getdrv.interface = interface;
1555 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1557 if (errno == ENODATA)
1559 else if (errno == ENODEV)
1560 return LIBUSB_ERROR_NO_DEVICE;
1562 usbi_err(HANDLE_CTX(handle),
1563 "get driver failed error %d errno %d", r, errno);
1564 return LIBUSB_ERROR_OTHER;
1567 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1570 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1573 int fd = _device_handle_priv(handle)->fd;
1574 struct usbfs_ioctl command;
1575 struct usbfs_getdriver getdrv;
1578 command.ifno = interface;
1579 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1580 command.data = NULL;
1582 getdrv.interface = interface;
1583 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1584 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1585 return LIBUSB_ERROR_NOT_FOUND;
1587 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1589 if (errno == ENODATA)
1590 return LIBUSB_ERROR_NOT_FOUND;
1591 else if (errno == EINVAL)
1592 return LIBUSB_ERROR_INVALID_PARAM;
1593 else if (errno == ENODEV)
1594 return LIBUSB_ERROR_NO_DEVICE;
1596 usbi_err(HANDLE_CTX(handle),
1597 "detach failed error %d errno %d", r, errno);
1598 return LIBUSB_ERROR_OTHER;
1604 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1607 int fd = _device_handle_priv(handle)->fd;
1608 struct usbfs_ioctl command;
1611 command.ifno = interface;
1612 command.ioctl_code = IOCTL_USBFS_CONNECT;
1613 command.data = NULL;
1615 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1617 if (errno == ENODATA)
1618 return LIBUSB_ERROR_NOT_FOUND;
1619 else if (errno == EINVAL)
1620 return LIBUSB_ERROR_INVALID_PARAM;
1621 else if (errno == ENODEV)
1622 return LIBUSB_ERROR_NO_DEVICE;
1623 else if (errno == EBUSY)
1624 return LIBUSB_ERROR_BUSY;
1626 usbi_err(HANDLE_CTX(handle),
1627 "attach failed error %d errno %d", r, errno);
1628 return LIBUSB_ERROR_OTHER;
1629 } else if (r == 0) {
1630 return LIBUSB_ERROR_NOT_FOUND;
1636 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1639 struct usbfs_disconnect_claim dc;
1640 int r, fd = _device_handle_priv(handle)->fd;
1642 dc.interface = interface;
1643 strcpy(dc.driver, "usbfs");
1644 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1645 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1646 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1652 return LIBUSB_ERROR_BUSY;
1654 return LIBUSB_ERROR_INVALID_PARAM;
1656 return LIBUSB_ERROR_NO_DEVICE;
1658 usbi_err(HANDLE_CTX(handle),
1659 "disconnect-and-claim failed errno %d", errno);
1660 return LIBUSB_ERROR_OTHER;
1663 /* Fallback code for kernels which don't support the
1664 disconnect-and-claim ioctl */
1665 r = op_detach_kernel_driver(handle, interface);
1666 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1669 return claim_interface(handle, interface);
1672 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1674 if (handle->auto_detach_kernel_driver)
1675 return detach_kernel_driver_and_claim(handle, iface);
1677 return claim_interface(handle, iface);
1680 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1684 r = release_interface(handle, iface);
1688 if (handle->auto_detach_kernel_driver)
1689 op_attach_kernel_driver(handle, iface);
1694 static void op_destroy_device(struct libusb_device *dev)
1696 struct linux_device_priv *priv = _device_priv(dev);
1697 if (priv->descriptors)
1698 free(priv->descriptors);
1699 if (priv->sysfs_dir)
1700 free(priv->sysfs_dir);
1703 /* URBs are discarded in reverse order of submission to avoid races. */
1704 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1706 struct libusb_transfer *transfer =
1707 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1708 struct linux_transfer_priv *tpriv =
1709 usbi_transfer_get_os_priv(itransfer);
1710 struct linux_device_handle_priv *dpriv =
1711 _device_handle_priv(transfer->dev_handle);
1713 struct usbfs_urb *urb;
1715 for (i = last_plus_one - 1; i >= first; i--) {
1716 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1717 urb = tpriv->iso_urbs[i];
1719 urb = &tpriv->urbs[i];
1721 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1724 if (EINVAL == errno) {
1725 usbi_dbg("URB not found --> assuming ready to be reaped");
1726 if (i == (last_plus_one - 1))
1727 ret = LIBUSB_ERROR_NOT_FOUND;
1728 } else if (ENODEV == errno) {
1729 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1730 ret = LIBUSB_ERROR_NO_DEVICE;
1732 usbi_warn(TRANSFER_CTX(transfer),
1733 "unrecognised discard errno %d", errno);
1734 ret = LIBUSB_ERROR_OTHER;
1740 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1743 for (i = 0; i < tpriv->num_urbs; i++) {
1744 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1750 free(tpriv->iso_urbs);
1751 tpriv->iso_urbs = NULL;
1754 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1756 struct libusb_transfer *transfer =
1757 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1758 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1759 struct linux_device_handle_priv *dpriv =
1760 _device_handle_priv(transfer->dev_handle);
1761 struct usbfs_urb *urbs;
1762 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1763 == LIBUSB_ENDPOINT_OUT;
1764 int bulk_buffer_len, use_bulk_continuation;
1770 return LIBUSB_ERROR_BUSY;
1772 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1773 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1774 return LIBUSB_ERROR_NOT_SUPPORTED;
1777 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1778 * around this by splitting large transfers into 16k blocks, and then
1779 * submit all urbs at once. it would be simpler to submit one urb at
1780 * a time, but there is a big performance gain doing it this way.
1782 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1783 * using arbritary large transfers can still be a bad idea though, as
1784 * the kernel needs to allocate physical contiguous memory for this,
1785 * which may fail for large buffers.
1787 * The kernel solves this problem by splitting the transfer into
1788 * blocks itself when the host-controller is scatter-gather capable
1789 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1791 * Last, there is the issue of short-transfers when splitting, for
1792 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1793 * is needed, but this is not always available.
1795 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1796 /* Good! Just submit everything in one go */
1797 bulk_buffer_len = transfer->length ? transfer->length : 1;
1798 use_bulk_continuation = 0;
1799 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1800 /* Split the transfers and use bulk-continuation to
1801 avoid issues with short-transfers */
1802 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1803 use_bulk_continuation = 1;
1804 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1805 /* Don't split, assume the kernel can alloc the buffer
1806 (otherwise the submit will fail with -ENOMEM) */
1807 bulk_buffer_len = transfer->length ? transfer->length : 1;
1808 use_bulk_continuation = 0;
1810 /* Bad, splitting without bulk-continuation, short transfers
1811 which end before the last urb will not work reliable! */
1812 /* Note we don't warn here as this is "normal" on kernels <
1813 2.6.32 and not a problem for most applications */
1814 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1815 use_bulk_continuation = 0;
1818 int num_urbs = transfer->length / bulk_buffer_len;
1819 int last_urb_partial = 0;
1821 if (transfer->length == 0) {
1823 } else if ((transfer->length % bulk_buffer_len) > 0) {
1824 last_urb_partial = 1;
1827 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1829 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1830 urbs = calloc(1, alloc_size);
1832 return LIBUSB_ERROR_NO_MEM;
1834 tpriv->num_urbs = num_urbs;
1835 tpriv->num_retired = 0;
1836 tpriv->reap_action = NORMAL;
1837 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1839 for (i = 0; i < num_urbs; i++) {
1840 struct usbfs_urb *urb = &urbs[i];
1841 urb->usercontext = itransfer;
1842 switch (transfer->type) {
1843 case LIBUSB_TRANSFER_TYPE_BULK:
1844 urb->type = USBFS_URB_TYPE_BULK;
1847 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1848 urb->type = USBFS_URB_TYPE_BULK;
1849 urb->stream_id = itransfer->stream_id;
1851 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1852 urb->type = USBFS_URB_TYPE_INTERRUPT;
1855 urb->endpoint = transfer->endpoint;
1856 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1857 /* don't set the short not ok flag for the last URB */
1858 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1859 urb->flags = USBFS_URB_SHORT_NOT_OK;
1860 if (i == num_urbs - 1 && last_urb_partial)
1861 urb->buffer_length = transfer->length % bulk_buffer_len;
1862 else if (transfer->length == 0)
1863 urb->buffer_length = 0;
1865 urb->buffer_length = bulk_buffer_len;
1867 if (i > 0 && use_bulk_continuation)
1868 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1870 /* we have already checked that the flag is supported */
1871 if (is_out && i == num_urbs - 1 &&
1872 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1873 urb->flags |= USBFS_URB_ZERO_PACKET;
1875 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1877 if (errno == ENODEV) {
1878 r = LIBUSB_ERROR_NO_DEVICE;
1880 usbi_err(TRANSFER_CTX(transfer),
1881 "submiturb failed error %d errno=%d", r, errno);
1882 r = LIBUSB_ERROR_IO;
1885 /* if the first URB submission fails, we can simply free up and
1886 * return failure immediately. */
1888 usbi_dbg("first URB failed, easy peasy");
1894 /* if it's not the first URB that failed, the situation is a bit
1895 * tricky. we may need to discard all previous URBs. there are
1897 * - discarding is asynchronous - discarded urbs will be reaped
1898 * later. the user must not have freed the transfer when the
1899 * discarded URBs are reaped, otherwise libusb will be using
1901 * - the earlier URBs may have completed successfully and we do
1902 * not want to throw away any data.
1903 * - this URB failing may be no error; EREMOTEIO means that
1904 * this transfer simply didn't need all the URBs we submitted
1905 * so, we report that the transfer was submitted successfully and
1906 * in case of error we discard all previous URBs. later when
1907 * the final reap completes we can report error to the user,
1908 * or success if an earlier URB was completed successfully.
1910 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1912 /* The URBs we haven't submitted yet we count as already
1914 tpriv->num_retired += num_urbs - i;
1916 /* If we completed short then don't try to discard. */
1917 if (COMPLETED_EARLY == tpriv->reap_action)
1920 discard_urbs(itransfer, 0, i);
1922 usbi_dbg("reporting successful submission but waiting for %d "
1923 "discards before reporting error", i);
1931 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1933 struct libusb_transfer *transfer =
1934 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1935 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1936 struct linux_device_handle_priv *dpriv =
1937 _device_handle_priv(transfer->dev_handle);
1938 struct usbfs_urb **urbs;
1940 int num_packets = transfer->num_iso_packets;
1942 int this_urb_len = 0;
1944 int packet_offset = 0;
1945 unsigned int packet_len;
1946 unsigned char *urb_buffer = transfer->buffer;
1948 if (tpriv->iso_urbs)
1949 return LIBUSB_ERROR_BUSY;
1951 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1952 * into smaller units to meet such restriction, then fire off all the
1953 * units at once. it would be simpler if we just fired one unit at a time,
1954 * but there is a big performance gain through doing it this way.
1956 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1957 * using arbritary large transfers is still be a bad idea though, as
1958 * the kernel needs to allocate physical contiguous memory for this,
1959 * which may fail for large buffers.
1962 /* calculate how many URBs we need */
1963 for (i = 0; i < num_packets; i++) {
1964 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1965 packet_len = transfer->iso_packet_desc[i].length;
1967 if (packet_len > space_remaining) {
1969 this_urb_len = packet_len;
1971 this_urb_len += packet_len;
1974 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1976 alloc_size = num_urbs * sizeof(*urbs);
1977 urbs = calloc(1, alloc_size);
1979 return LIBUSB_ERROR_NO_MEM;
1981 tpriv->iso_urbs = urbs;
1982 tpriv->num_urbs = num_urbs;
1983 tpriv->num_retired = 0;
1984 tpriv->reap_action = NORMAL;
1985 tpriv->iso_packet_offset = 0;
1987 /* allocate + initialize each URB with the correct number of packets */
1988 for (i = 0; i < num_urbs; i++) {
1989 struct usbfs_urb *urb;
1990 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1991 int urb_packet_offset = 0;
1992 unsigned char *urb_buffer_orig = urb_buffer;
1996 /* swallow up all the packets we can fit into this URB */
1997 while (packet_offset < transfer->num_iso_packets) {
1998 packet_len = transfer->iso_packet_desc[packet_offset].length;
1999 if (packet_len <= space_remaining_in_urb) {
2001 urb_packet_offset++;
2003 space_remaining_in_urb -= packet_len;
2004 urb_buffer += packet_len;
2006 /* it can't fit, save it for the next URB */
2011 alloc_size = sizeof(*urb)
2012 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2013 urb = calloc(1, alloc_size);
2015 free_iso_urbs(tpriv);
2016 return LIBUSB_ERROR_NO_MEM;
2020 /* populate packet lengths */
2021 for (j = 0, k = packet_offset - urb_packet_offset;
2022 k < packet_offset; k++, j++) {
2023 packet_len = transfer->iso_packet_desc[k].length;
2024 urb->iso_frame_desc[j].length = packet_len;
2027 urb->usercontext = itransfer;
2028 urb->type = USBFS_URB_TYPE_ISO;
2029 /* FIXME: interface for non-ASAP data? */
2030 urb->flags = USBFS_URB_ISO_ASAP;
2031 urb->endpoint = transfer->endpoint;
2032 urb->number_of_packets = urb_packet_offset;
2033 urb->buffer = urb_buffer_orig;
2037 for (i = 0; i < num_urbs; i++) {
2038 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2040 if (errno == ENODEV) {
2041 r = LIBUSB_ERROR_NO_DEVICE;
2043 usbi_err(TRANSFER_CTX(transfer),
2044 "submiturb failed error %d errno=%d", r, errno);
2045 r = LIBUSB_ERROR_IO;
2048 /* if the first URB submission fails, we can simply free up and
2049 * return failure immediately. */
2051 usbi_dbg("first URB failed, easy peasy");
2052 free_iso_urbs(tpriv);
2056 /* if it's not the first URB that failed, the situation is a bit
2057 * tricky. we must discard all previous URBs. there are
2059 * - discarding is asynchronous - discarded urbs will be reaped
2060 * later. the user must not have freed the transfer when the
2061 * discarded URBs are reaped, otherwise libusb will be using
2063 * - the earlier URBs may have completed successfully and we do
2064 * not want to throw away any data.
2065 * so, in this case we discard all the previous URBs BUT we report
2066 * that the transfer was submitted successfully. then later when
2067 * the final discard completes we can report error to the user.
2069 tpriv->reap_action = SUBMIT_FAILED;
2071 /* The URBs we haven't submitted yet we count as already
2073 tpriv->num_retired = num_urbs - i;
2074 discard_urbs(itransfer, 0, i);
2076 usbi_dbg("reporting successful submission but waiting for %d "
2077 "discards before reporting error", i);
2085 static int submit_control_transfer(struct usbi_transfer *itransfer)
2087 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2088 struct libusb_transfer *transfer =
2089 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2090 struct linux_device_handle_priv *dpriv =
2091 _device_handle_priv(transfer->dev_handle);
2092 struct usbfs_urb *urb;
2096 return LIBUSB_ERROR_BUSY;
2098 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2099 return LIBUSB_ERROR_INVALID_PARAM;
2101 urb = calloc(1, sizeof(struct usbfs_urb));
2103 return LIBUSB_ERROR_NO_MEM;
2105 tpriv->num_urbs = 1;
2106 tpriv->reap_action = NORMAL;
2108 urb->usercontext = itransfer;
2109 urb->type = USBFS_URB_TYPE_CONTROL;
2110 urb->endpoint = transfer->endpoint;
2111 urb->buffer = transfer->buffer;
2112 urb->buffer_length = transfer->length;
2114 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2118 if (errno == ENODEV)
2119 return LIBUSB_ERROR_NO_DEVICE;
2121 usbi_err(TRANSFER_CTX(transfer),
2122 "submiturb failed error %d errno=%d", r, errno);
2123 return LIBUSB_ERROR_IO;
2128 static int op_submit_transfer(struct usbi_transfer *itransfer)
2130 struct libusb_transfer *transfer =
2131 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2133 switch (transfer->type) {
2134 case LIBUSB_TRANSFER_TYPE_CONTROL:
2135 return submit_control_transfer(itransfer);
2136 case LIBUSB_TRANSFER_TYPE_BULK:
2137 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2138 return submit_bulk_transfer(itransfer);
2139 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2140 return submit_bulk_transfer(itransfer);
2141 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2142 return submit_iso_transfer(itransfer);
2144 usbi_err(TRANSFER_CTX(transfer),
2145 "unknown endpoint type %d", transfer->type);
2146 return LIBUSB_ERROR_INVALID_PARAM;
2150 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2152 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2153 struct libusb_transfer *transfer =
2154 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2156 switch (transfer->type) {
2157 case LIBUSB_TRANSFER_TYPE_BULK:
2158 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2159 if (tpriv->reap_action == ERROR)
2161 /* else, fall through */
2162 case LIBUSB_TRANSFER_TYPE_CONTROL:
2163 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2164 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2165 tpriv->reap_action = CANCELLED;
2168 usbi_err(TRANSFER_CTX(transfer),
2169 "unknown endpoint type %d", transfer->type);
2170 return LIBUSB_ERROR_INVALID_PARAM;
2174 return LIBUSB_ERROR_NOT_FOUND;
2176 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2179 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2181 struct libusb_transfer *transfer =
2182 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2183 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2185 /* urbs can be freed also in submit_transfer so lock mutex first */
2186 switch (transfer->type) {
2187 case LIBUSB_TRANSFER_TYPE_CONTROL:
2188 case LIBUSB_TRANSFER_TYPE_BULK:
2189 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2190 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2191 usbi_mutex_lock(&itransfer->lock);
2195 usbi_mutex_unlock(&itransfer->lock);
2197 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2198 usbi_mutex_lock(&itransfer->lock);
2199 if (tpriv->iso_urbs)
2200 free_iso_urbs(tpriv);
2201 usbi_mutex_unlock(&itransfer->lock);
2204 usbi_err(TRANSFER_CTX(transfer),
2205 "unknown endpoint type %d", transfer->type);
2209 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2210 struct usbfs_urb *urb)
2212 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2213 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2214 int urb_idx = urb - tpriv->urbs;
2216 usbi_mutex_lock(&itransfer->lock);
2217 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2218 urb_idx + 1, tpriv->num_urbs);
2220 tpriv->num_retired++;
2222 if (tpriv->reap_action != NORMAL) {
2223 /* cancelled, submit_fail, or completed early */
2224 usbi_dbg("abnormal reap: urb status %d", urb->status);
2226 /* even though we're in the process of cancelling, it's possible that
2227 * we may receive some data in these URBs that we don't want to lose.
2229 * 1. while the kernel is cancelling all the packets that make up an
2230 * URB, a few of them might complete. so we get back a successful
2231 * cancellation *and* some data.
2232 * 2. we receive a short URB which marks the early completion condition,
2233 * so we start cancelling the remaining URBs. however, we're too
2234 * slow and another URB completes (or at least completes partially).
2235 * (this can't happen since we always use BULK_CONTINUATION.)
2237 * When this happens, our objectives are not to lose any "surplus" data,
2238 * and also to stick it at the end of the previously-received data
2239 * (closing any holes), so that libusb reports the total amount of
2240 * transferred data and presents it in a contiguous chunk.
2242 if (urb->actual_length > 0) {
2243 unsigned char *target = transfer->buffer + itransfer->transferred;
2244 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2245 if (urb->buffer != target) {
2246 usbi_dbg("moving surplus data from offset %d to offset %d",
2247 (unsigned char *) urb->buffer - transfer->buffer,
2248 target - transfer->buffer);
2249 memmove(target, urb->buffer, urb->actual_length);
2251 itransfer->transferred += urb->actual_length;
2254 if (tpriv->num_retired == tpriv->num_urbs) {
2255 usbi_dbg("abnormal reap: last URB handled, reporting");
2256 if (tpriv->reap_action != COMPLETED_EARLY &&
2257 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2258 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2264 itransfer->transferred += urb->actual_length;
2266 /* Many of these errors can occur on *any* urb of a multi-urb
2267 * transfer. When they do, we tear down the rest of the transfer.
2269 switch (urb->status) {
2272 case -EREMOTEIO: /* short transfer */
2274 case -ENOENT: /* cancelled */
2279 usbi_dbg("device removed");
2280 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2281 goto cancel_remaining;
2283 usbi_dbg("detected endpoint stall");
2284 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2285 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2286 goto cancel_remaining;
2288 /* overflow can only ever occur in the last urb */
2289 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2290 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2291 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2298 usbi_dbg("low level error %d", urb->status);
2299 tpriv->reap_action = ERROR;
2300 goto cancel_remaining;
2302 usbi_warn(ITRANSFER_CTX(itransfer),
2303 "unrecognised urb status %d", urb->status);
2304 tpriv->reap_action = ERROR;
2305 goto cancel_remaining;
2308 /* if we're the last urb or we got less data than requested then we're
2310 if (urb_idx == tpriv->num_urbs - 1) {
2311 usbi_dbg("last URB in transfer --> complete!");
2313 } else if (urb->actual_length < urb->buffer_length) {
2314 usbi_dbg("short transfer %d/%d --> complete!",
2315 urb->actual_length, urb->buffer_length);
2316 if (tpriv->reap_action == NORMAL)
2317 tpriv->reap_action = COMPLETED_EARLY;
2322 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2323 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2325 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2328 /* cancel remaining urbs and wait for their completion before
2329 * reporting results */
2330 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2333 usbi_mutex_unlock(&itransfer->lock);
2339 usbi_mutex_unlock(&itransfer->lock);
2340 return CANCELLED == tpriv->reap_action ?
2341 usbi_handle_transfer_cancellation(itransfer) :
2342 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2345 static int handle_iso_completion(struct usbi_transfer *itransfer,
2346 struct usbfs_urb *urb)
2348 struct libusb_transfer *transfer =
2349 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2350 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2351 int num_urbs = tpriv->num_urbs;
2354 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2356 usbi_mutex_lock(&itransfer->lock);
2357 for (i = 0; i < num_urbs; i++) {
2358 if (urb == tpriv->iso_urbs[i]) {
2364 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2365 usbi_mutex_unlock(&itransfer->lock);
2366 return LIBUSB_ERROR_NOT_FOUND;
2369 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2372 /* copy isochronous results back in */
2374 for (i = 0; i < urb->number_of_packets; i++) {
2375 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2376 struct libusb_iso_packet_descriptor *lib_desc =
2377 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2378 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2379 switch (urb_desc->status) {
2382 case -ENOENT: /* cancelled */
2387 usbi_dbg("device removed");
2388 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2391 usbi_dbg("detected endpoint stall");
2392 lib_desc->status = LIBUSB_TRANSFER_STALL;
2395 usbi_dbg("overflow error");
2396 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2404 usbi_dbg("low-level USB error %d", urb_desc->status);
2405 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2408 usbi_warn(TRANSFER_CTX(transfer),
2409 "unrecognised urb status %d", urb_desc->status);
2410 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2413 lib_desc->actual_length = urb_desc->actual_length;
2416 tpriv->num_retired++;
2418 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2419 usbi_dbg("CANCEL: urb status %d", urb->status);
2421 if (tpriv->num_retired == num_urbs) {
2422 usbi_dbg("CANCEL: last URB handled, reporting");
2423 free_iso_urbs(tpriv);
2424 if (tpriv->reap_action == CANCELLED) {
2425 usbi_mutex_unlock(&itransfer->lock);
2426 return usbi_handle_transfer_cancellation(itransfer);
2428 usbi_mutex_unlock(&itransfer->lock);
2429 return usbi_handle_transfer_completion(itransfer,
2430 LIBUSB_TRANSFER_ERROR);
2436 switch (urb->status) {
2439 case -ENOENT: /* cancelled */
2443 usbi_dbg("device removed");
2444 status = LIBUSB_TRANSFER_NO_DEVICE;
2447 usbi_warn(TRANSFER_CTX(transfer),
2448 "unrecognised urb status %d", urb->status);
2449 status = LIBUSB_TRANSFER_ERROR;
2453 /* if we're the last urb then we're done */
2454 if (urb_idx == num_urbs) {
2455 usbi_dbg("last URB in transfer --> complete!");
2456 free_iso_urbs(tpriv);
2457 usbi_mutex_unlock(&itransfer->lock);
2458 return usbi_handle_transfer_completion(itransfer, status);
2462 usbi_mutex_unlock(&itransfer->lock);
2466 static int handle_control_completion(struct usbi_transfer *itransfer,
2467 struct usbfs_urb *urb)
2469 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2472 usbi_mutex_lock(&itransfer->lock);
2473 usbi_dbg("handling completion status %d", urb->status);
2475 itransfer->transferred += urb->actual_length;
2477 if (tpriv->reap_action == CANCELLED) {
2478 if (urb->status != 0 && urb->status != -ENOENT)
2479 usbi_warn(ITRANSFER_CTX(itransfer),
2480 "cancel: unrecognised urb status %d", urb->status);
2483 usbi_mutex_unlock(&itransfer->lock);
2484 return usbi_handle_transfer_cancellation(itransfer);
2487 switch (urb->status) {
2489 status = LIBUSB_TRANSFER_COMPLETED;
2491 case -ENOENT: /* cancelled */
2492 status = LIBUSB_TRANSFER_CANCELLED;
2496 usbi_dbg("device removed");
2497 status = LIBUSB_TRANSFER_NO_DEVICE;
2500 usbi_dbg("unsupported control request");
2501 status = LIBUSB_TRANSFER_STALL;
2504 usbi_dbg("control overflow error");
2505 status = LIBUSB_TRANSFER_OVERFLOW;
2512 usbi_dbg("low-level bus error occurred");
2513 status = LIBUSB_TRANSFER_ERROR;
2516 usbi_warn(ITRANSFER_CTX(itransfer),
2517 "unrecognised urb status %d", urb->status);
2518 status = LIBUSB_TRANSFER_ERROR;
2524 usbi_mutex_unlock(&itransfer->lock);
2525 return usbi_handle_transfer_completion(itransfer, status);
2528 static int reap_for_handle(struct libusb_device_handle *handle)
2530 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2532 struct usbfs_urb *urb;
2533 struct usbi_transfer *itransfer;
2534 struct libusb_transfer *transfer;
2536 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2537 if (r == -1 && errno == EAGAIN)
2540 if (errno == ENODEV)
2541 return LIBUSB_ERROR_NO_DEVICE;
2543 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2545 return LIBUSB_ERROR_IO;
2548 itransfer = urb->usercontext;
2549 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2551 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2552 urb->actual_length);
2554 switch (transfer->type) {
2555 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2556 return handle_iso_completion(itransfer, urb);
2557 case LIBUSB_TRANSFER_TYPE_BULK:
2558 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2559 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2560 return handle_bulk_completion(itransfer, urb);
2561 case LIBUSB_TRANSFER_TYPE_CONTROL:
2562 return handle_control_completion(itransfer, urb);
2564 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2566 return LIBUSB_ERROR_OTHER;
2570 static int op_handle_events(struct libusb_context *ctx,
2571 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2576 usbi_mutex_lock(&ctx->open_devs_lock);
2577 for (i = 0; i < nfds && num_ready > 0; i++) {
2578 struct pollfd *pollfd = &fds[i];
2579 struct libusb_device_handle *handle;
2580 struct linux_device_handle_priv *hpriv = NULL;
2582 if (!pollfd->revents)
2586 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2587 hpriv = _device_handle_priv(handle);
2588 if (hpriv->fd == pollfd->fd)
2592 if (!hpriv || hpriv->fd != pollfd->fd) {
2593 usbi_err(ctx, "cannot find handle for fd %d\n",
2598 if (pollfd->revents & POLLERR) {
2599 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2600 usbi_handle_disconnect(handle);
2601 /* device will still be marked as attached if hotplug monitor thread
2602 * hasn't processed remove event yet */
2603 usbi_mutex_static_lock(&linux_hotplug_lock);
2604 if (handle->dev->attached)
2605 linux_device_disconnected(handle->dev->bus_number,
2606 handle->dev->device_address, NULL);
2607 usbi_mutex_static_unlock(&linux_hotplug_lock);
2612 r = reap_for_handle(handle);
2614 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2622 usbi_mutex_unlock(&ctx->open_devs_lock);
2626 static int op_clock_gettime(int clk_id, struct timespec *tp)
2629 case USBI_CLOCK_MONOTONIC:
2630 return clock_gettime(monotonic_clkid, tp);
2631 case USBI_CLOCK_REALTIME:
2632 return clock_gettime(CLOCK_REALTIME, tp);
2634 return LIBUSB_ERROR_INVALID_PARAM;
2638 #ifdef USBI_TIMERFD_AVAILABLE
2639 static clockid_t op_get_timerfd_clockid(void)
2641 return monotonic_clkid;
2646 const struct usbi_os_backend linux_usbfs_backend = {
2647 .name = "Linux usbfs",
2648 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER|USBI_CAP_HAS_POLLABLE_DEVICE_FD,
2651 .get_device_list = NULL,
2652 .hotplug_poll = op_hotplug_poll,
2653 .get_device_descriptor = op_get_device_descriptor,
2654 .get_active_config_descriptor = op_get_active_config_descriptor,
2655 .get_config_descriptor = op_get_config_descriptor,
2656 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2660 .get_configuration = op_get_configuration,
2661 .set_configuration = op_set_configuration,
2662 .claim_interface = op_claim_interface,
2663 .release_interface = op_release_interface,
2665 .set_interface_altsetting = op_set_interface,
2666 .clear_halt = op_clear_halt,
2667 .reset_device = op_reset_device,
2669 .alloc_streams = op_alloc_streams,
2670 .free_streams = op_free_streams,
2672 .kernel_driver_active = op_kernel_driver_active,
2673 .detach_kernel_driver = op_detach_kernel_driver,
2674 .attach_kernel_driver = op_attach_kernel_driver,
2676 .destroy_device = op_destroy_device,
2678 .submit_transfer = op_submit_transfer,
2679 .cancel_transfer = op_cancel_transfer,
2680 .clear_transfer_priv = op_clear_transfer_priv,
2682 .handle_events = op_handle_events,
2684 .clock_gettime = op_clock_gettime,
2686 #ifdef USBI_TIMERFD_AVAILABLE
2687 .get_timerfd_clockid = op_get_timerfd_clockid,
2690 .device_priv_size = sizeof(struct linux_device_priv),
2691 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2692 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2693 .add_iso_packet_size = 0,