1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
43 #include "linux_usbfs.h"
46 * opening a usbfs node causes the device to be resumed, so we attempt to
47 * avoid this during enumeration.
49 * sysfs allows us to read the kernel's in-memory copies of device descriptors
50 * and so forth, avoiding the need to open the device:
51 * - The binary "descriptors" file contains all config descriptors since
52 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
53 * - The binary "descriptors" file was added in 2.6.23, commit
54 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
55 * active config descriptors
56 * - The "busnum" file was added in 2.6.22, commit
57 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
58 * - The "devnum" file has been present since pre-2.6.18
59 * - the "bConfigurationValue" file has been present since pre-2.6.18
61 * If we have bConfigurationValue, busnum, and devnum, then we can determine
62 * the active configuration without having to open the usbfs node in RDWR mode.
63 * The busnum file is important as that is the only way we can relate sysfs
64 * devices to usbfs nodes.
66 * If we also have all descriptors, we can obtain the device descriptor and
67 * configuration without touching usbfs at all.
70 /* endianness for multi-byte fields:
72 * Descriptors exposed by usbfs have the multi-byte fields in the device
73 * descriptor as host endian. Multi-byte fields in the other descriptors are
74 * bus-endian. The kernel documentation says otherwise, but it is wrong.
76 * In sysfs all descriptors are bus-endian.
79 static const char *usbfs_path = NULL;
81 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
82 static int usbdev_names = 0;
84 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
85 * allows us to mark URBs as being part of a specific logical transfer when
86 * we submit them to the kernel. then, on any error except a cancellation, all
87 * URBs within that transfer will be cancelled and no more URBs will be
88 * accepted for the transfer, meaning that no more data can creep in.
90 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
91 * (in either direction) except the first.
92 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
93 * last; it means that the kernel should treat a short reply as an error.
94 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
95 * transfers can't be short unless there's already some sort of error), and
96 * setting this flag is disallowed (a kernel with USB debugging enabled will
99 static int supports_flag_bulk_continuation = -1;
101 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
102 * allows us to mark URBs that should be followed by a zero length data
103 * packet, which can be required by device- or class-specific protocols.
105 static int supports_flag_zero_packet = -1;
107 /* clock ID for monotonic clock, as not all clock sources are available on all
108 * systems. appropriate choice made at initialization time. */
109 static clockid_t monotonic_clkid = -1;
111 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
112 * to sysfs, so we can relate devices. This also implies that we can read
113 * the active configuration through bConfigurationValue */
114 static int sysfs_can_relate_devices = -1;
116 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
117 * config descriptors (rather then just the active config) to the sysfs
118 * descriptors file, so from then on we can use them. */
119 static int sysfs_has_descriptors = -1;
121 /* how many times have we initted (and not exited) ? */
122 static int init_count = 0;
124 /* Serialize hotplug start/stop */
125 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
126 /* Serialize scan-devices, event-thread, and poll */
127 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
129 static int linux_start_event_monitor(void);
130 static int linux_stop_event_monitor(void);
131 static int linux_scan_devices(struct libusb_context *ctx);
132 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
133 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
135 #if !defined(USE_UDEV)
136 static int linux_default_scan_devices (struct libusb_context *ctx);
139 struct linux_device_priv {
141 unsigned char *descriptors;
143 int active_config; /* cache val for !sysfs_can_relate_devices */
146 struct linux_device_handle_priv {
154 /* submission failed after the first URB, so await cancellation/completion
155 * of all the others */
158 /* cancelled by user or timeout */
161 /* completed multi-URB transfer in non-final URB */
164 /* one or more urbs encountered a low-level error */
168 struct linux_transfer_priv {
170 struct usbfs_urb *urbs;
171 struct usbfs_urb **iso_urbs;
174 enum reap_action reap_action;
177 enum libusb_transfer_status reap_status;
179 /* next iso packet in user-supplied transfer to be populated */
180 int iso_packet_offset;
183 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
185 struct libusb_context *ctx = DEVICE_CTX(dev);
191 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
192 usbfs_path, dev->bus_number, dev->device_address);
194 snprintf(path, PATH_MAX, "%s/%03d/%03d",
195 usbfs_path, dev->bus_number, dev->device_address);
197 fd = open(path, mode);
199 return fd; /* Success */
201 if (errno == ENOENT) {
203 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
205 /* Wait 10ms for USB device path creation.*/
206 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
208 fd = open(path, mode);
210 return fd; /* Success */
214 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
215 path, strerror(errno));
216 if (errno == EACCES && mode == O_RDWR)
217 usbi_err(ctx, "libusb requires write access to USB "
222 return LIBUSB_ERROR_ACCESS;
224 return LIBUSB_ERROR_NO_DEVICE;
225 return LIBUSB_ERROR_IO;
228 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
230 return (struct linux_device_priv *) dev->os_priv;
233 static struct linux_device_handle_priv *_device_handle_priv(
234 struct libusb_device_handle *handle)
236 return (struct linux_device_handle_priv *) handle->os_priv;
239 /* check dirent for a /dev/usbdev%d.%d name
240 * optionally return bus/device on success */
241 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
245 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
248 usbi_dbg("found: %s", entry->d_name);
256 static int check_usb_vfs(const char *dirname)
259 struct dirent *entry;
262 dir = opendir(dirname);
266 while ((entry = readdir(dir)) != NULL) {
267 if (entry->d_name[0] == '.')
270 /* We assume if we find any files that it must be the right place */
279 static const char *find_usbfs_path(void)
281 const char *path = "/dev/bus/usb";
282 const char *ret = NULL;
284 if (check_usb_vfs(path)) {
287 path = "/proc/bus/usb";
288 if (check_usb_vfs(path))
292 /* look for /dev/usbdev*.* if the normal places fail */
294 struct dirent *entry;
300 while ((entry = readdir(dir)) != NULL) {
301 if (_is_usbdev_entry(entry, NULL, NULL)) {
302 /* found one; that's enough */
312 /* On udev based systems without any usb-devices /dev/bus/usb will not
313 * exist. So if we've not found anything and we're using udev for hotplug
314 * simply assume /dev/bus/usb rather then making libusb_init fail. */
315 #if defined(USE_UDEV)
317 ret = "/dev/bus/usb";
321 usbi_dbg("found usbfs at %s", ret);
326 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
327 * seem to lack it). fall back to REALTIME if we have to. */
328 static clockid_t find_monotonic_clock(void)
330 #ifdef CLOCK_MONOTONIC
334 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
335 * because it's not available through timerfd */
336 r = clock_gettime(CLOCK_MONOTONIC, &ts);
338 return CLOCK_MONOTONIC;
339 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
342 return CLOCK_REALTIME;
345 static int kernel_version_ge(int major, int minor, int sublevel)
348 int atoms, kmajor, kminor, ksublevel;
352 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
361 /* kmajor == major */
363 return 0 == minor && 0 == sublevel;
369 /* kminor == minor */
371 return 0 == sublevel;
373 return ksublevel >= sublevel;
376 static int op_init(struct libusb_context *ctx)
381 usbfs_path = find_usbfs_path();
383 usbi_err(ctx, "could not find usbfs");
384 return LIBUSB_ERROR_OTHER;
387 if (monotonic_clkid == -1)
388 monotonic_clkid = find_monotonic_clock();
390 if (supports_flag_bulk_continuation == -1) {
391 /* bulk continuation URB flag available from Linux 2.6.32 */
392 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
393 if (supports_flag_bulk_continuation == -1) {
394 usbi_err(ctx, "error checking for bulk continuation support");
395 return LIBUSB_ERROR_OTHER;
399 if (supports_flag_bulk_continuation)
400 usbi_dbg("bulk continuation flag supported");
402 if (-1 == supports_flag_zero_packet) {
403 /* zero length packet URB flag fixed since Linux 2.6.31 */
404 supports_flag_zero_packet = kernel_version_ge(2,6,31);
405 if (-1 == supports_flag_zero_packet) {
406 usbi_err(ctx, "error checking for zero length packet support");
407 return LIBUSB_ERROR_OTHER;
411 if (supports_flag_zero_packet)
412 usbi_dbg("zero length packet flag supported");
414 if (-1 == sysfs_has_descriptors) {
415 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
416 sysfs_has_descriptors = kernel_version_ge(2,6,26);
417 if (-1 == sysfs_has_descriptors) {
418 usbi_err(ctx, "error checking for sysfs descriptors");
419 return LIBUSB_ERROR_OTHER;
423 if (-1 == sysfs_can_relate_devices) {
424 /* sysfs has busnum since Linux 2.6.22 */
425 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
426 if (-1 == sysfs_can_relate_devices) {
427 usbi_err(ctx, "error checking for sysfs busnum");
428 return LIBUSB_ERROR_OTHER;
432 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
433 r = stat(SYSFS_DEVICE_PATH, &statbuf);
434 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
435 usbi_warn(ctx, "sysfs not mounted");
436 sysfs_can_relate_devices = 0;
437 sysfs_has_descriptors = 0;
441 if (sysfs_can_relate_devices)
442 usbi_dbg("sysfs can relate devices");
444 if (sysfs_has_descriptors)
445 usbi_dbg("sysfs has complete descriptors");
447 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
449 if (init_count == 0) {
450 /* start up hotplug event handler */
451 r = linux_start_event_monitor();
453 if (r == LIBUSB_SUCCESS) {
454 r = linux_scan_devices(ctx);
455 if (r == LIBUSB_SUCCESS)
457 else if (init_count == 0)
458 linux_stop_event_monitor();
460 usbi_err(ctx, "error starting hotplug event monitor");
461 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
466 static void op_exit(void)
468 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
469 assert(init_count != 0);
471 /* tear down event handler */
472 (void)linux_stop_event_monitor();
474 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
477 static int linux_start_event_monitor(void)
479 #if defined(USE_UDEV)
480 return linux_udev_start_event_monitor();
482 return linux_netlink_start_event_monitor();
486 static int linux_stop_event_monitor(void)
488 #if defined(USE_UDEV)
489 return linux_udev_stop_event_monitor();
491 return linux_netlink_stop_event_monitor();
495 static int linux_scan_devices(struct libusb_context *ctx)
499 usbi_mutex_static_lock(&linux_hotplug_lock);
501 #if defined(USE_UDEV)
502 ret = linux_udev_scan_devices(ctx);
504 ret = linux_default_scan_devices(ctx);
507 usbi_mutex_static_unlock(&linux_hotplug_lock);
512 static void op_hotplug_poll(void)
514 #if defined(USE_UDEV)
515 linux_udev_hotplug_poll();
517 linux_netlink_hotplug_poll();
521 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
523 struct linux_device_priv *priv = _device_priv(dev);
524 char filename[PATH_MAX];
527 snprintf(filename, PATH_MAX, "%s/%s/%s",
528 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
529 fd = open(filename, O_RDONLY);
531 usbi_err(DEVICE_CTX(dev),
532 "open %s failed ret=%d errno=%d", filename, fd, errno);
533 return LIBUSB_ERROR_IO;
539 /* Note only suitable for attributes which always read >= 0, < 0 is error */
540 static int __read_sysfs_attr(struct libusb_context *ctx,
541 const char *devname, const char *attr)
543 char filename[PATH_MAX];
547 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
549 f = fopen(filename, "r");
551 if (errno == ENOENT) {
552 /* File doesn't exist. Assume the device has been
553 disconnected (see trac ticket #70). */
554 return LIBUSB_ERROR_NO_DEVICE;
556 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
557 return LIBUSB_ERROR_IO;
560 r = fscanf(f, "%d", &value);
563 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
564 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
567 usbi_err(ctx, "%s contains a negative value", filename);
568 return LIBUSB_ERROR_IO;
574 static int op_get_device_descriptor(struct libusb_device *dev,
575 unsigned char *buffer, int *host_endian)
577 struct linux_device_priv *priv = _device_priv(dev);
579 *host_endian = sysfs_has_descriptors ? 0 : 1;
580 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
585 /* read the bConfigurationValue for a device */
586 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
589 char tmp[5] = {0, 0, 0, 0, 0};
594 fd = _open_sysfs_attr(dev, "bConfigurationValue");
598 r = read(fd, tmp, sizeof(tmp));
601 usbi_err(DEVICE_CTX(dev),
602 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
603 return LIBUSB_ERROR_IO;
605 usbi_dbg("device unconfigured");
610 if (tmp[sizeof(tmp) - 1] != 0) {
611 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
612 return LIBUSB_ERROR_IO;
613 } else if (tmp[0] == 0) {
614 usbi_err(DEVICE_CTX(dev), "no configuration value?");
615 return LIBUSB_ERROR_IO;
618 num = strtol(tmp, &endptr, 10);
620 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
621 return LIBUSB_ERROR_IO;
628 int linux_get_device_address (struct libusb_context *ctx, int detached,
629 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
630 const char *sys_name)
634 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
635 /* can't use sysfs to read the bus and device number if the
636 * device has been detached */
637 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
638 if (NULL == dev_node) {
639 return LIBUSB_ERROR_OTHER;
642 /* will this work with all supported kernel versions? */
643 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
644 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
645 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
646 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
649 return LIBUSB_SUCCESS;
652 usbi_dbg("scan %s", sys_name);
654 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
657 if (sysfs_attr > 255)
658 return LIBUSB_ERROR_INVALID_PARAM;
659 *busnum = (uint8_t) sysfs_attr;
661 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
664 if (sysfs_attr > 255)
665 return LIBUSB_ERROR_INVALID_PARAM;
667 *devaddr = (uint8_t) sysfs_attr;
669 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
671 return LIBUSB_SUCCESS;
674 /* Return offset of the next descriptor with the given type */
675 static int seek_to_next_descriptor(struct libusb_context *ctx,
676 uint8_t descriptor_type, unsigned char *buffer, int size)
678 struct usb_descriptor_header header;
681 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
683 return LIBUSB_ERROR_NOT_FOUND;
686 usbi_err(ctx, "short descriptor read %d/2", size);
687 return LIBUSB_ERROR_IO;
689 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
691 if (i && header.bDescriptorType == descriptor_type)
694 usbi_err(ctx, "bLength overflow by %d bytes", -size);
695 return LIBUSB_ERROR_IO;
698 /* Return offset to next config */
699 static int seek_to_next_config(struct libusb_context *ctx,
700 unsigned char *buffer, int size)
702 struct libusb_config_descriptor config;
705 return LIBUSB_ERROR_NOT_FOUND;
707 if (size < LIBUSB_DT_CONFIG_SIZE) {
708 usbi_err(ctx, "short descriptor read %d/%d",
709 size, LIBUSB_DT_CONFIG_SIZE);
710 return LIBUSB_ERROR_IO;
713 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
714 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
715 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
716 config.bDescriptorType);
717 return LIBUSB_ERROR_IO;
721 * In usbfs the config descriptors are config.wTotalLength bytes apart,
722 * with any short reads from the device appearing as holes in the file.
724 * In sysfs wTotalLength is ignored, instead the kernel returns a
725 * config descriptor with verified bLength fields, with descriptors
726 * with an invalid bLength removed.
728 if (sysfs_has_descriptors) {
729 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
731 if (next == LIBUSB_ERROR_NOT_FOUND)
736 if (next != config.wTotalLength)
737 usbi_warn(ctx, "config length mismatch wTotalLength "
738 "%d real %d", config.wTotalLength, next);
741 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
742 usbi_err(ctx, "invalid wTotalLength %d",
743 config.wTotalLength);
744 return LIBUSB_ERROR_IO;
745 } else if (config.wTotalLength > size) {
746 usbi_warn(ctx, "short descriptor read %d/%d",
747 size, config.wTotalLength);
750 return config.wTotalLength;
754 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
755 uint8_t value, unsigned char **buffer, int *host_endian)
757 struct libusb_context *ctx = DEVICE_CTX(dev);
758 struct linux_device_priv *priv = _device_priv(dev);
759 unsigned char *descriptors = priv->descriptors;
760 int size = priv->descriptors_len;
761 struct libusb_config_descriptor *config;
764 /* Unlike the device desc. config descs. are always in raw format */
767 /* Skip device header */
768 descriptors += DEVICE_DESC_LENGTH;
769 size -= DEVICE_DESC_LENGTH;
771 /* Seek till the config is found, or till "EOF" */
773 int next = seek_to_next_config(ctx, descriptors, size);
776 config = (struct libusb_config_descriptor *)descriptors;
777 if (config->bConfigurationValue == value) {
778 *buffer = descriptors;
786 static int op_get_active_config_descriptor(struct libusb_device *dev,
787 unsigned char *buffer, size_t len, int *host_endian)
790 unsigned char *config_desc;
792 if (sysfs_can_relate_devices) {
793 r = sysfs_get_active_config(dev, &config);
797 /* Use cached bConfigurationValue */
798 struct linux_device_priv *priv = _device_priv(dev);
799 config = priv->active_config;
802 return LIBUSB_ERROR_NOT_FOUND;
804 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
810 memcpy(buffer, config_desc, len);
814 static int op_get_config_descriptor(struct libusb_device *dev,
815 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
817 struct linux_device_priv *priv = _device_priv(dev);
818 unsigned char *descriptors = priv->descriptors;
819 int i, r, size = priv->descriptors_len;
821 /* Unlike the device desc. config descs. are always in raw format */
824 /* Skip device header */
825 descriptors += DEVICE_DESC_LENGTH;
826 size -= DEVICE_DESC_LENGTH;
828 /* Seek till the config is found, or till "EOF" */
830 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
833 if (i == config_index)
840 memcpy(buffer, descriptors, len);
844 /* send a control message to retrieve active configuration */
845 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
847 struct linux_device_priv *priv = _device_priv(dev);
848 unsigned char active_config = 0;
851 struct usbfs_ctrltransfer ctrl = {
852 .bmRequestType = LIBUSB_ENDPOINT_IN,
853 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
858 .data = &active_config
861 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
864 return LIBUSB_ERROR_NO_DEVICE;
866 /* we hit this error path frequently with buggy devices :( */
867 usbi_warn(DEVICE_CTX(dev),
868 "get_configuration failed ret=%d errno=%d", r, errno);
869 priv->active_config = -1;
871 if (active_config > 0) {
872 priv->active_config = active_config;
874 /* some buggy devices have a configuration 0, but we're
875 * reaching into the corner of a corner case here, so let's
876 * not support buggy devices in these circumstances.
877 * stick to the specs: a configuration value of 0 means
879 usbi_warn(DEVICE_CTX(dev),
880 "active cfg 0? assuming unconfigured device");
881 priv->active_config = -1;
885 return LIBUSB_SUCCESS;
888 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
889 uint8_t devaddr, const char *sysfs_dir)
891 struct linux_device_priv *priv = _device_priv(dev);
892 struct libusb_context *ctx = DEVICE_CTX(dev);
893 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
897 dev->bus_number = busnum;
898 dev->device_address = devaddr;
901 priv->sysfs_dir = strdup(sysfs_dir);
902 if (!priv->sysfs_dir)
903 return LIBUSB_ERROR_NO_MEM;
905 /* Note speed can contain 1.5, in this case __read_sysfs_attr
906 will stop parsing at the '.' and return 1 */
907 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
910 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
911 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
912 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
913 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
915 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
920 /* cache descriptors in memory */
921 if (sysfs_has_descriptors)
922 fd = _open_sysfs_attr(dev, "descriptors");
924 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
929 descriptors_size *= 2;
930 priv->descriptors = usbi_reallocf(priv->descriptors,
932 if (!priv->descriptors) {
934 return LIBUSB_ERROR_NO_MEM;
936 /* usbfs has holes in the file */
937 if (!sysfs_has_descriptors) {
938 memset(priv->descriptors + priv->descriptors_len,
939 0, descriptors_size - priv->descriptors_len);
941 r = read(fd, priv->descriptors + priv->descriptors_len,
942 descriptors_size - priv->descriptors_len);
944 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
947 return LIBUSB_ERROR_IO;
949 priv->descriptors_len += r;
950 } while (priv->descriptors_len == descriptors_size);
954 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
955 usbi_err(ctx, "short descriptor read (%d)",
956 priv->descriptors_len);
957 return LIBUSB_ERROR_IO;
960 if (sysfs_can_relate_devices)
961 return LIBUSB_SUCCESS;
963 /* cache active config */
964 fd = _get_usbfs_fd(dev, O_RDWR, 1);
966 /* cannot send a control message to determine the active
967 * config. just assume the first one is active. */
968 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
969 "active configuration descriptor");
970 if (priv->descriptors_len >=
971 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
972 struct libusb_config_descriptor config;
973 usbi_parse_descriptor(
974 priv->descriptors + DEVICE_DESC_LENGTH,
975 "bbwbbbbb", &config, 0);
976 priv->active_config = config.bConfigurationValue;
978 priv->active_config = -1; /* No config dt */
980 return LIBUSB_SUCCESS;
983 r = usbfs_get_active_config(dev, fd);
989 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
991 struct libusb_context *ctx = DEVICE_CTX(dev);
992 struct libusb_device *it;
993 char *parent_sysfs_dir, *tmp;
994 int ret, add_parent = 1;
996 /* XXX -- can we figure out the topology when using usbfs? */
997 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
998 /* either using usbfs or finding the parent of a root hub */
999 return LIBUSB_SUCCESS;
1002 parent_sysfs_dir = strdup(sysfs_dir);
1003 if (NULL == parent_sysfs_dir) {
1004 return LIBUSB_ERROR_NO_MEM;
1006 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1007 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1008 dev->port_number = atoi(tmp + 1);
1011 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1013 free (parent_sysfs_dir);
1014 return LIBUSB_SUCCESS;
1017 /* is the parent a root hub? */
1018 if (NULL == strchr(parent_sysfs_dir, '-')) {
1019 tmp = parent_sysfs_dir;
1020 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1023 return LIBUSB_ERROR_NO_MEM;
1028 /* find the parent in the context */
1029 usbi_mutex_lock(&ctx->usb_devs_lock);
1030 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1031 struct linux_device_priv *priv = _device_priv(it);
1032 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1033 dev->parent_dev = libusb_ref_device(it);
1037 usbi_mutex_unlock(&ctx->usb_devs_lock);
1039 if (!dev->parent_dev && add_parent) {
1040 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1042 sysfs_scan_device(ctx, parent_sysfs_dir);
1047 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1048 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1050 free (parent_sysfs_dir);
1052 return LIBUSB_SUCCESS;
1055 int linux_enumerate_device(struct libusb_context *ctx,
1056 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1058 unsigned long session_id;
1059 struct libusb_device *dev;
1062 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1063 * will be reused. instead we should add a simple sysfs attribute with
1065 session_id = busnum << 8 | devaddr;
1066 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1069 dev = usbi_get_device_by_session_id(ctx, session_id);
1071 /* device already exists in the context */
1072 usbi_dbg("session_id %ld already exists", session_id);
1073 libusb_unref_device(dev);
1074 return LIBUSB_SUCCESS;
1077 usbi_dbg("allocating new device for %d/%d (session %ld)",
1078 busnum, devaddr, session_id);
1079 dev = usbi_alloc_device(ctx, session_id);
1081 return LIBUSB_ERROR_NO_MEM;
1083 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1086 r = usbi_sanitize_device(dev);
1090 r = linux_get_parent_info(dev, sysfs_dir);
1095 libusb_unref_device(dev);
1097 usbi_connect_device(dev);
1102 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1104 struct libusb_context *ctx;
1106 usbi_mutex_static_lock(&active_contexts_lock);
1107 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1108 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1110 usbi_mutex_static_unlock(&active_contexts_lock);
1113 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1115 struct libusb_context *ctx;
1116 struct libusb_device *dev;
1117 unsigned long session_id = busnum << 8 | devaddr;
1119 usbi_mutex_static_lock(&active_contexts_lock);
1120 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1121 dev = usbi_get_device_by_session_id (ctx, session_id);
1123 usbi_disconnect_device (dev);
1124 libusb_unref_device(dev);
1126 usbi_dbg("device not found for session %x", session_id);
1129 usbi_mutex_static_unlock(&active_contexts_lock);
1132 #if !defined(USE_UDEV)
1133 /* open a bus directory and adds all discovered devices to the context */
1134 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1137 char dirpath[PATH_MAX];
1138 struct dirent *entry;
1139 int r = LIBUSB_ERROR_IO;
1141 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1142 usbi_dbg("%s", dirpath);
1143 dir = opendir(dirpath);
1145 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1146 /* FIXME: should handle valid race conditions like hub unplugged
1147 * during directory iteration - this is not an error */
1151 while ((entry = readdir(dir))) {
1154 if (entry->d_name[0] == '.')
1157 devaddr = atoi(entry->d_name);
1159 usbi_dbg("unknown dir entry %s", entry->d_name);
1163 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1164 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1175 static int usbfs_get_device_list(struct libusb_context *ctx)
1177 struct dirent *entry;
1178 DIR *buses = opendir(usbfs_path);
1182 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1183 return LIBUSB_ERROR_IO;
1186 while ((entry = readdir(buses))) {
1189 if (entry->d_name[0] == '.')
1194 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1197 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1199 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1203 busnum = atoi(entry->d_name);
1205 usbi_dbg("unknown dir entry %s", entry->d_name);
1209 r = usbfs_scan_busdir(ctx, busnum);
1221 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1223 uint8_t busnum, devaddr;
1226 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1227 if (LIBUSB_SUCCESS != ret) {
1231 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1235 #if !defined(USE_UDEV)
1236 static int sysfs_get_device_list(struct libusb_context *ctx)
1238 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1239 struct dirent *entry;
1240 int r = LIBUSB_ERROR_IO;
1243 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1247 while ((entry = readdir(devices))) {
1248 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1249 || strchr(entry->d_name, ':'))
1252 if (sysfs_scan_device(ctx, entry->d_name)) {
1253 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1264 static int linux_default_scan_devices (struct libusb_context *ctx)
1266 /* we can retrieve device list and descriptors from sysfs or usbfs.
1267 * sysfs is preferable, because if we use usbfs we end up resuming
1268 * any autosuspended USB devices. however, sysfs is not available
1269 * everywhere, so we need a usbfs fallback too.
1271 * as described in the "sysfs vs usbfs" comment at the top of this
1272 * file, sometimes we have sysfs but not enough information to
1273 * relate sysfs devices to usbfs nodes. op_init() determines the
1274 * adequacy of sysfs and sets sysfs_can_relate_devices.
1276 if (sysfs_can_relate_devices != 0)
1277 return sysfs_get_device_list(ctx);
1279 return usbfs_get_device_list(ctx);
1283 static int op_open(struct libusb_device_handle *handle)
1285 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1288 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1289 if (hpriv->fd < 0) {
1290 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1291 /* device will still be marked as attached if hotplug monitor thread
1292 * hasn't processed remove event yet */
1293 usbi_mutex_static_lock(&linux_hotplug_lock);
1294 if (handle->dev->attached) {
1295 usbi_dbg("open failed with no device, but device still attached");
1296 linux_device_disconnected(handle->dev->bus_number,
1297 handle->dev->device_address);
1299 usbi_mutex_static_unlock(&linux_hotplug_lock);
1304 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1306 if (errno == ENOTTY)
1307 usbi_dbg("getcap not available");
1309 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1311 if (supports_flag_zero_packet)
1312 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1313 if (supports_flag_bulk_continuation)
1314 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1317 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1324 static void op_close(struct libusb_device_handle *dev_handle)
1326 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1327 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1328 if (!hpriv->fd_removed)
1329 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1333 static int op_get_configuration(struct libusb_device_handle *handle,
1338 if (sysfs_can_relate_devices) {
1339 r = sysfs_get_active_config(handle->dev, config);
1341 r = usbfs_get_active_config(handle->dev,
1342 _device_handle_priv(handle)->fd);
1343 if (r == LIBUSB_SUCCESS)
1344 *config = _device_priv(handle->dev)->active_config;
1349 if (*config == -1) {
1350 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1357 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1359 struct linux_device_priv *priv = _device_priv(handle->dev);
1360 int fd = _device_handle_priv(handle)->fd;
1361 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1363 if (errno == EINVAL)
1364 return LIBUSB_ERROR_NOT_FOUND;
1365 else if (errno == EBUSY)
1366 return LIBUSB_ERROR_BUSY;
1367 else if (errno == ENODEV)
1368 return LIBUSB_ERROR_NO_DEVICE;
1370 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1371 return LIBUSB_ERROR_OTHER;
1374 /* update our cached active config descriptor */
1375 priv->active_config = config;
1377 return LIBUSB_SUCCESS;
1380 static int claim_interface(struct libusb_device_handle *handle, int iface)
1382 int fd = _device_handle_priv(handle)->fd;
1383 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1385 if (errno == ENOENT)
1386 return LIBUSB_ERROR_NOT_FOUND;
1387 else if (errno == EBUSY)
1388 return LIBUSB_ERROR_BUSY;
1389 else if (errno == ENODEV)
1390 return LIBUSB_ERROR_NO_DEVICE;
1392 usbi_err(HANDLE_CTX(handle),
1393 "claim interface failed, error %d errno %d", r, errno);
1394 return LIBUSB_ERROR_OTHER;
1399 static int release_interface(struct libusb_device_handle *handle, int iface)
1401 int fd = _device_handle_priv(handle)->fd;
1402 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1404 if (errno == ENODEV)
1405 return LIBUSB_ERROR_NO_DEVICE;
1407 usbi_err(HANDLE_CTX(handle),
1408 "release interface failed, error %d errno %d", r, errno);
1409 return LIBUSB_ERROR_OTHER;
1414 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1417 int fd = _device_handle_priv(handle)->fd;
1418 struct usbfs_setinterface setintf;
1421 setintf.interface = iface;
1422 setintf.altsetting = altsetting;
1423 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1425 if (errno == EINVAL)
1426 return LIBUSB_ERROR_NOT_FOUND;
1427 else if (errno == ENODEV)
1428 return LIBUSB_ERROR_NO_DEVICE;
1430 usbi_err(HANDLE_CTX(handle),
1431 "setintf failed error %d errno %d", r, errno);
1432 return LIBUSB_ERROR_OTHER;
1438 static int op_clear_halt(struct libusb_device_handle *handle,
1439 unsigned char endpoint)
1441 int fd = _device_handle_priv(handle)->fd;
1442 unsigned int _endpoint = endpoint;
1443 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1445 if (errno == ENOENT)
1446 return LIBUSB_ERROR_NOT_FOUND;
1447 else if (errno == ENODEV)
1448 return LIBUSB_ERROR_NO_DEVICE;
1450 usbi_err(HANDLE_CTX(handle),
1451 "clear_halt failed error %d errno %d", r, errno);
1452 return LIBUSB_ERROR_OTHER;
1458 static int op_reset_device(struct libusb_device_handle *handle)
1460 int fd = _device_handle_priv(handle)->fd;
1463 /* Doing a device reset will cause the usbfs driver to get unbound
1464 from any interfaces it is bound to. By voluntarily unbinding
1465 the usbfs driver ourself, we stop the kernel from rebinding
1466 the interface after reset (which would end up with the interface
1467 getting bound to the in kernel driver if any). */
1468 for (i = 0; i < USB_MAXINTERFACES; i++) {
1469 if (handle->claimed_interfaces & (1L << i)) {
1470 release_interface(handle, i);
1474 usbi_mutex_lock(&handle->lock);
1475 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1477 if (errno == ENODEV) {
1478 ret = LIBUSB_ERROR_NOT_FOUND;
1482 usbi_err(HANDLE_CTX(handle),
1483 "reset failed error %d errno %d", r, errno);
1484 ret = LIBUSB_ERROR_OTHER;
1488 /* And re-claim any interfaces which were claimed before the reset */
1489 for (i = 0; i < USB_MAXINTERFACES; i++) {
1490 if (handle->claimed_interfaces & (1L << i)) {
1492 * A driver may have completed modprobing during
1493 * IOCTL_USBFS_RESET, and bound itself as soon as
1494 * IOCTL_USBFS_RESET released the device lock
1496 r = detach_kernel_driver_and_claim(handle, i);
1498 usbi_warn(HANDLE_CTX(handle),
1499 "failed to re-claim interface %d after reset: %s",
1500 i, libusb_error_name(r));
1501 handle->claimed_interfaces &= ~(1L << i);
1502 ret = LIBUSB_ERROR_NOT_FOUND;
1507 usbi_mutex_unlock(&handle->lock);
1511 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1512 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1514 int r, fd = _device_handle_priv(handle)->fd;
1515 struct usbfs_streams *streams;
1517 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1518 return LIBUSB_ERROR_INVALID_PARAM;
1520 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1522 return LIBUSB_ERROR_NO_MEM;
1524 streams->num_streams = num_streams;
1525 streams->num_eps = num_endpoints;
1526 memcpy(streams->eps, endpoints, num_endpoints);
1528 r = ioctl(fd, req, streams);
1533 if (errno == ENOTTY)
1534 return LIBUSB_ERROR_NOT_SUPPORTED;
1535 else if (errno == EINVAL)
1536 return LIBUSB_ERROR_INVALID_PARAM;
1537 else if (errno == ENODEV)
1538 return LIBUSB_ERROR_NO_DEVICE;
1540 usbi_err(HANDLE_CTX(handle),
1541 "streams-ioctl failed error %d errno %d", r, errno);
1542 return LIBUSB_ERROR_OTHER;
1547 static int op_alloc_streams(struct libusb_device_handle *handle,
1548 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1550 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1551 num_streams, endpoints, num_endpoints);
1554 static int op_free_streams(struct libusb_device_handle *handle,
1555 unsigned char *endpoints, int num_endpoints)
1557 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1558 endpoints, num_endpoints);
1561 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1564 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1565 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1566 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1567 if (buffer == MAP_FAILED) {
1568 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1575 static int op_dev_mem_free(struct libusb_device_handle *handle,
1576 unsigned char *buffer, size_t len)
1578 if (munmap(buffer, len) != 0) {
1579 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1581 return LIBUSB_ERROR_OTHER;
1583 return LIBUSB_SUCCESS;
1587 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1590 int fd = _device_handle_priv(handle)->fd;
1591 struct usbfs_getdriver getdrv;
1594 getdrv.interface = interface;
1595 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1597 if (errno == ENODATA)
1599 else if (errno == ENODEV)
1600 return LIBUSB_ERROR_NO_DEVICE;
1602 usbi_err(HANDLE_CTX(handle),
1603 "get driver failed error %d errno %d", r, errno);
1604 return LIBUSB_ERROR_OTHER;
1607 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1610 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1613 int fd = _device_handle_priv(handle)->fd;
1614 struct usbfs_ioctl command;
1615 struct usbfs_getdriver getdrv;
1618 command.ifno = interface;
1619 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1620 command.data = NULL;
1622 getdrv.interface = interface;
1623 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1624 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1625 return LIBUSB_ERROR_NOT_FOUND;
1627 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1629 if (errno == ENODATA)
1630 return LIBUSB_ERROR_NOT_FOUND;
1631 else if (errno == EINVAL)
1632 return LIBUSB_ERROR_INVALID_PARAM;
1633 else if (errno == ENODEV)
1634 return LIBUSB_ERROR_NO_DEVICE;
1636 usbi_err(HANDLE_CTX(handle),
1637 "detach failed error %d errno %d", r, errno);
1638 return LIBUSB_ERROR_OTHER;
1644 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1647 int fd = _device_handle_priv(handle)->fd;
1648 struct usbfs_ioctl command;
1651 command.ifno = interface;
1652 command.ioctl_code = IOCTL_USBFS_CONNECT;
1653 command.data = NULL;
1655 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1657 if (errno == ENODATA)
1658 return LIBUSB_ERROR_NOT_FOUND;
1659 else if (errno == EINVAL)
1660 return LIBUSB_ERROR_INVALID_PARAM;
1661 else if (errno == ENODEV)
1662 return LIBUSB_ERROR_NO_DEVICE;
1663 else if (errno == EBUSY)
1664 return LIBUSB_ERROR_BUSY;
1666 usbi_err(HANDLE_CTX(handle),
1667 "attach failed error %d errno %d", r, errno);
1668 return LIBUSB_ERROR_OTHER;
1669 } else if (r == 0) {
1670 return LIBUSB_ERROR_NOT_FOUND;
1676 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1679 struct usbfs_disconnect_claim dc;
1680 int r, fd = _device_handle_priv(handle)->fd;
1682 dc.interface = interface;
1683 strcpy(dc.driver, "usbfs");
1684 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1685 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1686 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1692 return LIBUSB_ERROR_BUSY;
1694 return LIBUSB_ERROR_INVALID_PARAM;
1696 return LIBUSB_ERROR_NO_DEVICE;
1698 usbi_err(HANDLE_CTX(handle),
1699 "disconnect-and-claim failed errno %d", errno);
1700 return LIBUSB_ERROR_OTHER;
1703 /* Fallback code for kernels which don't support the
1704 disconnect-and-claim ioctl */
1705 r = op_detach_kernel_driver(handle, interface);
1706 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1709 return claim_interface(handle, interface);
1712 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1714 if (handle->auto_detach_kernel_driver)
1715 return detach_kernel_driver_and_claim(handle, iface);
1717 return claim_interface(handle, iface);
1720 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1724 r = release_interface(handle, iface);
1728 if (handle->auto_detach_kernel_driver)
1729 op_attach_kernel_driver(handle, iface);
1734 static void op_destroy_device(struct libusb_device *dev)
1736 struct linux_device_priv *priv = _device_priv(dev);
1737 if (priv->descriptors)
1738 free(priv->descriptors);
1739 if (priv->sysfs_dir)
1740 free(priv->sysfs_dir);
1743 /* URBs are discarded in reverse order of submission to avoid races. */
1744 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1746 struct libusb_transfer *transfer =
1747 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1748 struct linux_transfer_priv *tpriv =
1749 usbi_transfer_get_os_priv(itransfer);
1750 struct linux_device_handle_priv *dpriv =
1751 _device_handle_priv(transfer->dev_handle);
1753 struct usbfs_urb *urb;
1755 for (i = last_plus_one - 1; i >= first; i--) {
1756 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1757 urb = tpriv->iso_urbs[i];
1759 urb = &tpriv->urbs[i];
1761 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1764 if (EINVAL == errno) {
1765 usbi_dbg("URB not found --> assuming ready to be reaped");
1766 if (i == (last_plus_one - 1))
1767 ret = LIBUSB_ERROR_NOT_FOUND;
1768 } else if (ENODEV == errno) {
1769 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1770 ret = LIBUSB_ERROR_NO_DEVICE;
1772 usbi_warn(TRANSFER_CTX(transfer),
1773 "unrecognised discard errno %d", errno);
1774 ret = LIBUSB_ERROR_OTHER;
1780 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1783 for (i = 0; i < tpriv->num_urbs; i++) {
1784 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1790 free(tpriv->iso_urbs);
1791 tpriv->iso_urbs = NULL;
1794 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1796 struct libusb_transfer *transfer =
1797 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1798 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1799 struct linux_device_handle_priv *dpriv =
1800 _device_handle_priv(transfer->dev_handle);
1801 struct usbfs_urb *urbs;
1802 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1803 == LIBUSB_ENDPOINT_OUT;
1804 int bulk_buffer_len, use_bulk_continuation;
1808 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1809 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1810 return LIBUSB_ERROR_NOT_SUPPORTED;
1813 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1814 * around this by splitting large transfers into 16k blocks, and then
1815 * submit all urbs at once. it would be simpler to submit one urb at
1816 * a time, but there is a big performance gain doing it this way.
1818 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1819 * using arbritary large transfers can still be a bad idea though, as
1820 * the kernel needs to allocate physical contiguous memory for this,
1821 * which may fail for large buffers.
1823 * The kernel solves this problem by splitting the transfer into
1824 * blocks itself when the host-controller is scatter-gather capable
1825 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1827 * Last, there is the issue of short-transfers when splitting, for
1828 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1829 * is needed, but this is not always available.
1831 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1832 /* Good! Just submit everything in one go */
1833 bulk_buffer_len = transfer->length ? transfer->length : 1;
1834 use_bulk_continuation = 0;
1835 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1836 /* Split the transfers and use bulk-continuation to
1837 avoid issues with short-transfers */
1838 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1839 use_bulk_continuation = 1;
1840 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1841 /* Don't split, assume the kernel can alloc the buffer
1842 (otherwise the submit will fail with -ENOMEM) */
1843 bulk_buffer_len = transfer->length ? transfer->length : 1;
1844 use_bulk_continuation = 0;
1846 /* Bad, splitting without bulk-continuation, short transfers
1847 which end before the last urb will not work reliable! */
1848 /* Note we don't warn here as this is "normal" on kernels <
1849 2.6.32 and not a problem for most applications */
1850 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1851 use_bulk_continuation = 0;
1854 int num_urbs = transfer->length / bulk_buffer_len;
1855 int last_urb_partial = 0;
1857 if (transfer->length == 0) {
1859 } else if ((transfer->length % bulk_buffer_len) > 0) {
1860 last_urb_partial = 1;
1863 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1865 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1867 return LIBUSB_ERROR_NO_MEM;
1869 tpriv->num_urbs = num_urbs;
1870 tpriv->num_retired = 0;
1871 tpriv->reap_action = NORMAL;
1872 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1874 for (i = 0; i < num_urbs; i++) {
1875 struct usbfs_urb *urb = &urbs[i];
1876 urb->usercontext = itransfer;
1877 switch (transfer->type) {
1878 case LIBUSB_TRANSFER_TYPE_BULK:
1879 urb->type = USBFS_URB_TYPE_BULK;
1882 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1883 urb->type = USBFS_URB_TYPE_BULK;
1884 urb->stream_id = itransfer->stream_id;
1886 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1887 urb->type = USBFS_URB_TYPE_INTERRUPT;
1890 urb->endpoint = transfer->endpoint;
1891 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1892 /* don't set the short not ok flag for the last URB */
1893 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1894 urb->flags = USBFS_URB_SHORT_NOT_OK;
1895 if (i == num_urbs - 1 && last_urb_partial)
1896 urb->buffer_length = transfer->length % bulk_buffer_len;
1897 else if (transfer->length == 0)
1898 urb->buffer_length = 0;
1900 urb->buffer_length = bulk_buffer_len;
1902 if (i > 0 && use_bulk_continuation)
1903 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1905 /* we have already checked that the flag is supported */
1906 if (is_out && i == num_urbs - 1 &&
1907 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1908 urb->flags |= USBFS_URB_ZERO_PACKET;
1910 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1912 if (errno == ENODEV) {
1913 r = LIBUSB_ERROR_NO_DEVICE;
1915 usbi_err(TRANSFER_CTX(transfer),
1916 "submiturb failed error %d errno=%d", r, errno);
1917 r = LIBUSB_ERROR_IO;
1920 /* if the first URB submission fails, we can simply free up and
1921 * return failure immediately. */
1923 usbi_dbg("first URB failed, easy peasy");
1929 /* if it's not the first URB that failed, the situation is a bit
1930 * tricky. we may need to discard all previous URBs. there are
1932 * - discarding is asynchronous - discarded urbs will be reaped
1933 * later. the user must not have freed the transfer when the
1934 * discarded URBs are reaped, otherwise libusb will be using
1936 * - the earlier URBs may have completed successfully and we do
1937 * not want to throw away any data.
1938 * - this URB failing may be no error; EREMOTEIO means that
1939 * this transfer simply didn't need all the URBs we submitted
1940 * so, we report that the transfer was submitted successfully and
1941 * in case of error we discard all previous URBs. later when
1942 * the final reap completes we can report error to the user,
1943 * or success if an earlier URB was completed successfully.
1945 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1947 /* The URBs we haven't submitted yet we count as already
1949 tpriv->num_retired += num_urbs - i;
1951 /* If we completed short then don't try to discard. */
1952 if (COMPLETED_EARLY == tpriv->reap_action)
1955 discard_urbs(itransfer, 0, i);
1957 usbi_dbg("reporting successful submission but waiting for %d "
1958 "discards before reporting error", i);
1966 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1968 struct libusb_transfer *transfer =
1969 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1970 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1971 struct linux_device_handle_priv *dpriv =
1972 _device_handle_priv(transfer->dev_handle);
1973 struct usbfs_urb **urbs;
1975 int num_packets = transfer->num_iso_packets;
1977 int this_urb_len = 0;
1979 int packet_offset = 0;
1980 unsigned int packet_len;
1981 unsigned char *urb_buffer = transfer->buffer;
1983 /* usbfs places arbitrary limits on iso URBs. this limit has changed
1984 * at least three times, and it's difficult to accurately detect which
1985 * limit this running kernel might impose. so we attempt to submit
1986 * whatever the user has provided. if the kernel rejects the request
1987 * due to its size, we return an error indicating such to the user.
1990 /* calculate how many URBs we need */
1991 for (i = 0; i < num_packets; i++) {
1992 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1993 packet_len = transfer->iso_packet_desc[i].length;
1995 if (packet_len > space_remaining) {
1997 this_urb_len = packet_len;
1998 /* check that we can actually support this packet length */
1999 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2000 return LIBUSB_ERROR_INVALID_PARAM;
2002 this_urb_len += packet_len;
2005 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2007 urbs = calloc(num_urbs, sizeof(*urbs));
2009 return LIBUSB_ERROR_NO_MEM;
2011 tpriv->iso_urbs = urbs;
2012 tpriv->num_urbs = num_urbs;
2013 tpriv->num_retired = 0;
2014 tpriv->reap_action = NORMAL;
2015 tpriv->iso_packet_offset = 0;
2017 /* allocate + initialize each URB with the correct number of packets */
2018 for (i = 0; i < num_urbs; i++) {
2019 struct usbfs_urb *urb;
2020 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2021 int urb_packet_offset = 0;
2022 unsigned char *urb_buffer_orig = urb_buffer;
2026 /* swallow up all the packets we can fit into this URB */
2027 while (packet_offset < transfer->num_iso_packets) {
2028 packet_len = transfer->iso_packet_desc[packet_offset].length;
2029 if (packet_len <= space_remaining_in_urb) {
2031 urb_packet_offset++;
2033 space_remaining_in_urb -= packet_len;
2034 urb_buffer += packet_len;
2036 /* it can't fit, save it for the next URB */
2041 alloc_size = sizeof(*urb)
2042 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2043 urb = calloc(1, alloc_size);
2045 free_iso_urbs(tpriv);
2046 return LIBUSB_ERROR_NO_MEM;
2050 /* populate packet lengths */
2051 for (j = 0, k = packet_offset - urb_packet_offset;
2052 k < packet_offset; k++, j++) {
2053 packet_len = transfer->iso_packet_desc[k].length;
2054 urb->iso_frame_desc[j].length = packet_len;
2057 urb->usercontext = itransfer;
2058 urb->type = USBFS_URB_TYPE_ISO;
2059 /* FIXME: interface for non-ASAP data? */
2060 urb->flags = USBFS_URB_ISO_ASAP;
2061 urb->endpoint = transfer->endpoint;
2062 urb->number_of_packets = urb_packet_offset;
2063 urb->buffer = urb_buffer_orig;
2067 for (i = 0; i < num_urbs; i++) {
2068 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2070 if (errno == ENODEV) {
2071 r = LIBUSB_ERROR_NO_DEVICE;
2072 } else if (errno == EINVAL) {
2073 usbi_warn(TRANSFER_CTX(transfer),
2074 "submiturb failed, transfer too large");
2075 r = LIBUSB_ERROR_INVALID_PARAM;
2077 usbi_err(TRANSFER_CTX(transfer),
2078 "submiturb failed error %d errno=%d", r, errno);
2079 r = LIBUSB_ERROR_IO;
2082 /* if the first URB submission fails, we can simply free up and
2083 * return failure immediately. */
2085 usbi_dbg("first URB failed, easy peasy");
2086 free_iso_urbs(tpriv);
2090 /* if it's not the first URB that failed, the situation is a bit
2091 * tricky. we must discard all previous URBs. there are
2093 * - discarding is asynchronous - discarded urbs will be reaped
2094 * later. the user must not have freed the transfer when the
2095 * discarded URBs are reaped, otherwise libusb will be using
2097 * - the earlier URBs may have completed successfully and we do
2098 * not want to throw away any data.
2099 * so, in this case we discard all the previous URBs BUT we report
2100 * that the transfer was submitted successfully. then later when
2101 * the final discard completes we can report error to the user.
2103 tpriv->reap_action = SUBMIT_FAILED;
2105 /* The URBs we haven't submitted yet we count as already
2107 tpriv->num_retired = num_urbs - i;
2108 discard_urbs(itransfer, 0, i);
2110 usbi_dbg("reporting successful submission but waiting for %d "
2111 "discards before reporting error", i);
2119 static int submit_control_transfer(struct usbi_transfer *itransfer)
2121 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2122 struct libusb_transfer *transfer =
2123 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2124 struct linux_device_handle_priv *dpriv =
2125 _device_handle_priv(transfer->dev_handle);
2126 struct usbfs_urb *urb;
2129 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2130 return LIBUSB_ERROR_INVALID_PARAM;
2132 urb = calloc(1, sizeof(struct usbfs_urb));
2134 return LIBUSB_ERROR_NO_MEM;
2136 tpriv->num_urbs = 1;
2137 tpriv->reap_action = NORMAL;
2139 urb->usercontext = itransfer;
2140 urb->type = USBFS_URB_TYPE_CONTROL;
2141 urb->endpoint = transfer->endpoint;
2142 urb->buffer = transfer->buffer;
2143 urb->buffer_length = transfer->length;
2145 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2149 if (errno == ENODEV)
2150 return LIBUSB_ERROR_NO_DEVICE;
2152 usbi_err(TRANSFER_CTX(transfer),
2153 "submiturb failed error %d errno=%d", r, errno);
2154 return LIBUSB_ERROR_IO;
2159 static int op_submit_transfer(struct usbi_transfer *itransfer)
2161 struct libusb_transfer *transfer =
2162 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2164 switch (transfer->type) {
2165 case LIBUSB_TRANSFER_TYPE_CONTROL:
2166 return submit_control_transfer(itransfer);
2167 case LIBUSB_TRANSFER_TYPE_BULK:
2168 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2169 return submit_bulk_transfer(itransfer);
2170 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2171 return submit_bulk_transfer(itransfer);
2172 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2173 return submit_iso_transfer(itransfer);
2175 usbi_err(TRANSFER_CTX(transfer),
2176 "unknown endpoint type %d", transfer->type);
2177 return LIBUSB_ERROR_INVALID_PARAM;
2181 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2183 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2184 struct libusb_transfer *transfer =
2185 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2189 return LIBUSB_ERROR_NOT_FOUND;
2191 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2195 switch (transfer->type) {
2196 case LIBUSB_TRANSFER_TYPE_BULK:
2197 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2198 if (tpriv->reap_action == ERROR)
2200 /* else, fall through */
2202 tpriv->reap_action = CANCELLED;
2208 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2210 struct libusb_transfer *transfer =
2211 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2212 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2214 /* urbs can be freed also in submit_transfer so lock mutex first */
2215 switch (transfer->type) {
2216 case LIBUSB_TRANSFER_TYPE_CONTROL:
2217 case LIBUSB_TRANSFER_TYPE_BULK:
2218 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2219 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2225 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2226 if (tpriv->iso_urbs) {
2227 free_iso_urbs(tpriv);
2228 tpriv->iso_urbs = NULL;
2232 usbi_err(TRANSFER_CTX(transfer),
2233 "unknown endpoint type %d", transfer->type);
2237 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2238 struct usbfs_urb *urb)
2240 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2241 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2242 int urb_idx = urb - tpriv->urbs;
2244 usbi_mutex_lock(&itransfer->lock);
2245 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2246 urb_idx + 1, tpriv->num_urbs);
2248 tpriv->num_retired++;
2250 if (tpriv->reap_action != NORMAL) {
2251 /* cancelled, submit_fail, or completed early */
2252 usbi_dbg("abnormal reap: urb status %d", urb->status);
2254 /* even though we're in the process of cancelling, it's possible that
2255 * we may receive some data in these URBs that we don't want to lose.
2257 * 1. while the kernel is cancelling all the packets that make up an
2258 * URB, a few of them might complete. so we get back a successful
2259 * cancellation *and* some data.
2260 * 2. we receive a short URB which marks the early completion condition,
2261 * so we start cancelling the remaining URBs. however, we're too
2262 * slow and another URB completes (or at least completes partially).
2263 * (this can't happen since we always use BULK_CONTINUATION.)
2265 * When this happens, our objectives are not to lose any "surplus" data,
2266 * and also to stick it at the end of the previously-received data
2267 * (closing any holes), so that libusb reports the total amount of
2268 * transferred data and presents it in a contiguous chunk.
2270 if (urb->actual_length > 0) {
2271 unsigned char *target = transfer->buffer + itransfer->transferred;
2272 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2273 if (urb->buffer != target) {
2274 usbi_dbg("moving surplus data from offset %d to offset %d",
2275 (unsigned char *) urb->buffer - transfer->buffer,
2276 target - transfer->buffer);
2277 memmove(target, urb->buffer, urb->actual_length);
2279 itransfer->transferred += urb->actual_length;
2282 if (tpriv->num_retired == tpriv->num_urbs) {
2283 usbi_dbg("abnormal reap: last URB handled, reporting");
2284 if (tpriv->reap_action != COMPLETED_EARLY &&
2285 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2286 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2292 itransfer->transferred += urb->actual_length;
2294 /* Many of these errors can occur on *any* urb of a multi-urb
2295 * transfer. When they do, we tear down the rest of the transfer.
2297 switch (urb->status) {
2300 case -EREMOTEIO: /* short transfer */
2302 case -ENOENT: /* cancelled */
2307 usbi_dbg("device removed");
2308 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2309 goto cancel_remaining;
2311 usbi_dbg("detected endpoint stall");
2312 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2313 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2314 goto cancel_remaining;
2316 /* overflow can only ever occur in the last urb */
2317 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2318 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2319 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2326 usbi_dbg("low level error %d", urb->status);
2327 tpriv->reap_action = ERROR;
2328 goto cancel_remaining;
2330 usbi_warn(ITRANSFER_CTX(itransfer),
2331 "unrecognised urb status %d", urb->status);
2332 tpriv->reap_action = ERROR;
2333 goto cancel_remaining;
2336 /* if we're the last urb or we got less data than requested then we're
2338 if (urb_idx == tpriv->num_urbs - 1) {
2339 usbi_dbg("last URB in transfer --> complete!");
2341 } else if (urb->actual_length < urb->buffer_length) {
2342 usbi_dbg("short transfer %d/%d --> complete!",
2343 urb->actual_length, urb->buffer_length);
2344 if (tpriv->reap_action == NORMAL)
2345 tpriv->reap_action = COMPLETED_EARLY;
2350 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2351 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2353 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2356 /* cancel remaining urbs and wait for their completion before
2357 * reporting results */
2358 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2361 usbi_mutex_unlock(&itransfer->lock);
2367 usbi_mutex_unlock(&itransfer->lock);
2368 return CANCELLED == tpriv->reap_action ?
2369 usbi_handle_transfer_cancellation(itransfer) :
2370 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2373 static int handle_iso_completion(struct usbi_transfer *itransfer,
2374 struct usbfs_urb *urb)
2376 struct libusb_transfer *transfer =
2377 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2378 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2379 int num_urbs = tpriv->num_urbs;
2382 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2384 usbi_mutex_lock(&itransfer->lock);
2385 for (i = 0; i < num_urbs; i++) {
2386 if (urb == tpriv->iso_urbs[i]) {
2392 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2393 usbi_mutex_unlock(&itransfer->lock);
2394 return LIBUSB_ERROR_NOT_FOUND;
2397 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2400 /* copy isochronous results back in */
2402 for (i = 0; i < urb->number_of_packets; i++) {
2403 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2404 struct libusb_iso_packet_descriptor *lib_desc =
2405 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2406 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2407 switch (urb_desc->status) {
2410 case -ENOENT: /* cancelled */
2415 usbi_dbg("device removed");
2416 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2419 usbi_dbg("detected endpoint stall");
2420 lib_desc->status = LIBUSB_TRANSFER_STALL;
2423 usbi_dbg("overflow error");
2424 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2432 usbi_dbg("low-level USB error %d", urb_desc->status);
2433 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2436 usbi_warn(TRANSFER_CTX(transfer),
2437 "unrecognised urb status %d", urb_desc->status);
2438 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2441 lib_desc->actual_length = urb_desc->actual_length;
2444 tpriv->num_retired++;
2446 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2447 usbi_dbg("CANCEL: urb status %d", urb->status);
2449 if (tpriv->num_retired == num_urbs) {
2450 usbi_dbg("CANCEL: last URB handled, reporting");
2451 free_iso_urbs(tpriv);
2452 if (tpriv->reap_action == CANCELLED) {
2453 usbi_mutex_unlock(&itransfer->lock);
2454 return usbi_handle_transfer_cancellation(itransfer);
2456 usbi_mutex_unlock(&itransfer->lock);
2457 return usbi_handle_transfer_completion(itransfer,
2458 LIBUSB_TRANSFER_ERROR);
2464 switch (urb->status) {
2467 case -ENOENT: /* cancelled */
2471 usbi_dbg("device removed");
2472 status = LIBUSB_TRANSFER_NO_DEVICE;
2475 usbi_warn(TRANSFER_CTX(transfer),
2476 "unrecognised urb status %d", urb->status);
2477 status = LIBUSB_TRANSFER_ERROR;
2481 /* if we're the last urb then we're done */
2482 if (urb_idx == num_urbs) {
2483 usbi_dbg("last URB in transfer --> complete!");
2484 free_iso_urbs(tpriv);
2485 usbi_mutex_unlock(&itransfer->lock);
2486 return usbi_handle_transfer_completion(itransfer, status);
2490 usbi_mutex_unlock(&itransfer->lock);
2494 static int handle_control_completion(struct usbi_transfer *itransfer,
2495 struct usbfs_urb *urb)
2497 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2500 usbi_mutex_lock(&itransfer->lock);
2501 usbi_dbg("handling completion status %d", urb->status);
2503 itransfer->transferred += urb->actual_length;
2505 if (tpriv->reap_action == CANCELLED) {
2506 if (urb->status != 0 && urb->status != -ENOENT)
2507 usbi_warn(ITRANSFER_CTX(itransfer),
2508 "cancel: unrecognised urb status %d", urb->status);
2511 usbi_mutex_unlock(&itransfer->lock);
2512 return usbi_handle_transfer_cancellation(itransfer);
2515 switch (urb->status) {
2517 status = LIBUSB_TRANSFER_COMPLETED;
2519 case -ENOENT: /* cancelled */
2520 status = LIBUSB_TRANSFER_CANCELLED;
2524 usbi_dbg("device removed");
2525 status = LIBUSB_TRANSFER_NO_DEVICE;
2528 usbi_dbg("unsupported control request");
2529 status = LIBUSB_TRANSFER_STALL;
2532 usbi_dbg("control overflow error");
2533 status = LIBUSB_TRANSFER_OVERFLOW;
2540 usbi_dbg("low-level bus error occurred");
2541 status = LIBUSB_TRANSFER_ERROR;
2544 usbi_warn(ITRANSFER_CTX(itransfer),
2545 "unrecognised urb status %d", urb->status);
2546 status = LIBUSB_TRANSFER_ERROR;
2552 usbi_mutex_unlock(&itransfer->lock);
2553 return usbi_handle_transfer_completion(itransfer, status);
2556 static int reap_for_handle(struct libusb_device_handle *handle)
2558 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2560 struct usbfs_urb *urb;
2561 struct usbi_transfer *itransfer;
2562 struct libusb_transfer *transfer;
2564 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2565 if (r == -1 && errno == EAGAIN)
2568 if (errno == ENODEV)
2569 return LIBUSB_ERROR_NO_DEVICE;
2571 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2573 return LIBUSB_ERROR_IO;
2576 itransfer = urb->usercontext;
2577 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2579 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2580 urb->actual_length);
2582 switch (transfer->type) {
2583 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2584 return handle_iso_completion(itransfer, urb);
2585 case LIBUSB_TRANSFER_TYPE_BULK:
2586 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2587 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2588 return handle_bulk_completion(itransfer, urb);
2589 case LIBUSB_TRANSFER_TYPE_CONTROL:
2590 return handle_control_completion(itransfer, urb);
2592 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2594 return LIBUSB_ERROR_OTHER;
2598 static int op_handle_events(struct libusb_context *ctx,
2599 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2604 usbi_mutex_lock(&ctx->open_devs_lock);
2605 for (i = 0; i < nfds && num_ready > 0; i++) {
2606 struct pollfd *pollfd = &fds[i];
2607 struct libusb_device_handle *handle;
2608 struct linux_device_handle_priv *hpriv = NULL;
2610 if (!pollfd->revents)
2614 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2615 hpriv = _device_handle_priv(handle);
2616 if (hpriv->fd == pollfd->fd)
2620 if (!hpriv || hpriv->fd != pollfd->fd) {
2621 usbi_err(ctx, "cannot find handle for fd %d",
2626 if (pollfd->revents & POLLERR) {
2627 /* remove the fd from the pollfd set so that it doesn't continuously
2628 * trigger an event, and flag that it has been removed so op_close()
2629 * doesn't try to remove it a second time */
2630 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2631 hpriv->fd_removed = 1;
2633 /* device will still be marked as attached if hotplug monitor thread
2634 * hasn't processed remove event yet */
2635 usbi_mutex_static_lock(&linux_hotplug_lock);
2636 if (handle->dev->attached)
2637 linux_device_disconnected(handle->dev->bus_number,
2638 handle->dev->device_address);
2639 usbi_mutex_static_unlock(&linux_hotplug_lock);
2641 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2643 r = reap_for_handle(handle);
2647 usbi_handle_disconnect(handle);
2652 r = reap_for_handle(handle);
2654 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2662 usbi_mutex_unlock(&ctx->open_devs_lock);
2666 static int op_clock_gettime(int clk_id, struct timespec *tp)
2669 case USBI_CLOCK_MONOTONIC:
2670 return clock_gettime(monotonic_clkid, tp);
2671 case USBI_CLOCK_REALTIME:
2672 return clock_gettime(CLOCK_REALTIME, tp);
2674 return LIBUSB_ERROR_INVALID_PARAM;
2678 #ifdef USBI_TIMERFD_AVAILABLE
2679 static clockid_t op_get_timerfd_clockid(void)
2681 return monotonic_clkid;
2686 const struct usbi_os_backend linux_usbfs_backend = {
2687 .name = "Linux usbfs",
2688 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2691 .get_device_list = NULL,
2692 .hotplug_poll = op_hotplug_poll,
2693 .get_device_descriptor = op_get_device_descriptor,
2694 .get_active_config_descriptor = op_get_active_config_descriptor,
2695 .get_config_descriptor = op_get_config_descriptor,
2696 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2700 .get_configuration = op_get_configuration,
2701 .set_configuration = op_set_configuration,
2702 .claim_interface = op_claim_interface,
2703 .release_interface = op_release_interface,
2705 .set_interface_altsetting = op_set_interface,
2706 .clear_halt = op_clear_halt,
2707 .reset_device = op_reset_device,
2709 .alloc_streams = op_alloc_streams,
2710 .free_streams = op_free_streams,
2712 .dev_mem_alloc = op_dev_mem_alloc,
2713 .dev_mem_free = op_dev_mem_free,
2715 .kernel_driver_active = op_kernel_driver_active,
2716 .detach_kernel_driver = op_detach_kernel_driver,
2717 .attach_kernel_driver = op_attach_kernel_driver,
2719 .destroy_device = op_destroy_device,
2721 .submit_transfer = op_submit_transfer,
2722 .cancel_transfer = op_cancel_transfer,
2723 .clear_transfer_priv = op_clear_transfer_priv,
2725 .handle_events = op_handle_events,
2727 .clock_gettime = op_clock_gettime,
2729 #ifdef USBI_TIMERFD_AVAILABLE
2730 .get_timerfd_clockid = op_get_timerfd_clockid,
2733 .device_priv_size = sizeof(struct linux_device_priv),
2734 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2735 .transfer_priv_size = sizeof(struct linux_transfer_priv),