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 (priv->sysfs_dir) {
1033 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1034 dev->parent_dev = libusb_ref_device(it);
1039 usbi_mutex_unlock(&ctx->usb_devs_lock);
1041 if (!dev->parent_dev && add_parent) {
1042 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1044 sysfs_scan_device(ctx, parent_sysfs_dir);
1049 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1050 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1052 free (parent_sysfs_dir);
1054 return LIBUSB_SUCCESS;
1057 int linux_enumerate_device(struct libusb_context *ctx,
1058 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1060 unsigned long session_id;
1061 struct libusb_device *dev;
1064 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1065 * will be reused. instead we should add a simple sysfs attribute with
1067 session_id = busnum << 8 | devaddr;
1068 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1071 dev = usbi_get_device_by_session_id(ctx, session_id);
1073 /* device already exists in the context */
1074 usbi_dbg("session_id %ld already exists", session_id);
1075 libusb_unref_device(dev);
1076 return LIBUSB_SUCCESS;
1079 usbi_dbg("allocating new device for %d/%d (session %ld)",
1080 busnum, devaddr, session_id);
1081 dev = usbi_alloc_device(ctx, session_id);
1083 return LIBUSB_ERROR_NO_MEM;
1085 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1088 r = usbi_sanitize_device(dev);
1092 r = linux_get_parent_info(dev, sysfs_dir);
1097 libusb_unref_device(dev);
1099 usbi_connect_device(dev);
1104 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1106 struct libusb_context *ctx;
1108 usbi_mutex_static_lock(&active_contexts_lock);
1109 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1110 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1112 usbi_mutex_static_unlock(&active_contexts_lock);
1115 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1117 struct libusb_context *ctx;
1118 struct libusb_device *dev;
1119 unsigned long session_id = busnum << 8 | devaddr;
1121 usbi_mutex_static_lock(&active_contexts_lock);
1122 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1123 dev = usbi_get_device_by_session_id (ctx, session_id);
1125 usbi_disconnect_device (dev);
1126 libusb_unref_device(dev);
1128 usbi_dbg("device not found for session %x", session_id);
1131 usbi_mutex_static_unlock(&active_contexts_lock);
1134 #if !defined(USE_UDEV)
1135 /* open a bus directory and adds all discovered devices to the context */
1136 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1139 char dirpath[PATH_MAX];
1140 struct dirent *entry;
1141 int r = LIBUSB_ERROR_IO;
1143 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1144 usbi_dbg("%s", dirpath);
1145 dir = opendir(dirpath);
1147 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1148 /* FIXME: should handle valid race conditions like hub unplugged
1149 * during directory iteration - this is not an error */
1153 while ((entry = readdir(dir))) {
1156 if (entry->d_name[0] == '.')
1159 devaddr = atoi(entry->d_name);
1161 usbi_dbg("unknown dir entry %s", entry->d_name);
1165 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1166 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1177 static int usbfs_get_device_list(struct libusb_context *ctx)
1179 struct dirent *entry;
1180 DIR *buses = opendir(usbfs_path);
1184 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1185 return LIBUSB_ERROR_IO;
1188 while ((entry = readdir(buses))) {
1191 if (entry->d_name[0] == '.')
1196 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1199 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1201 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1205 busnum = atoi(entry->d_name);
1207 usbi_dbg("unknown dir entry %s", entry->d_name);
1211 r = usbfs_scan_busdir(ctx, busnum);
1223 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1225 uint8_t busnum, devaddr;
1228 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1229 if (LIBUSB_SUCCESS != ret) {
1233 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1237 #if !defined(USE_UDEV)
1238 static int sysfs_get_device_list(struct libusb_context *ctx)
1240 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1241 struct dirent *entry;
1242 int r = LIBUSB_ERROR_IO;
1245 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1249 while ((entry = readdir(devices))) {
1250 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1251 || strchr(entry->d_name, ':'))
1254 if (sysfs_scan_device(ctx, entry->d_name)) {
1255 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1266 static int linux_default_scan_devices (struct libusb_context *ctx)
1268 /* we can retrieve device list and descriptors from sysfs or usbfs.
1269 * sysfs is preferable, because if we use usbfs we end up resuming
1270 * any autosuspended USB devices. however, sysfs is not available
1271 * everywhere, so we need a usbfs fallback too.
1273 * as described in the "sysfs vs usbfs" comment at the top of this
1274 * file, sometimes we have sysfs but not enough information to
1275 * relate sysfs devices to usbfs nodes. op_init() determines the
1276 * adequacy of sysfs and sets sysfs_can_relate_devices.
1278 if (sysfs_can_relate_devices != 0)
1279 return sysfs_get_device_list(ctx);
1281 return usbfs_get_device_list(ctx);
1285 static int op_open(struct libusb_device_handle *handle)
1287 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1290 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1291 if (hpriv->fd < 0) {
1292 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1293 /* device will still be marked as attached if hotplug monitor thread
1294 * hasn't processed remove event yet */
1295 usbi_mutex_static_lock(&linux_hotplug_lock);
1296 if (handle->dev->attached) {
1297 usbi_dbg("open failed with no device, but device still attached");
1298 linux_device_disconnected(handle->dev->bus_number,
1299 handle->dev->device_address);
1301 usbi_mutex_static_unlock(&linux_hotplug_lock);
1306 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1308 if (errno == ENOTTY)
1309 usbi_dbg("getcap not available");
1311 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1313 if (supports_flag_zero_packet)
1314 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1315 if (supports_flag_bulk_continuation)
1316 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1319 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1326 static void op_close(struct libusb_device_handle *dev_handle)
1328 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1329 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1330 if (!hpriv->fd_removed)
1331 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1335 static int op_get_configuration(struct libusb_device_handle *handle,
1340 if (sysfs_can_relate_devices) {
1341 r = sysfs_get_active_config(handle->dev, config);
1343 r = usbfs_get_active_config(handle->dev,
1344 _device_handle_priv(handle)->fd);
1345 if (r == LIBUSB_SUCCESS)
1346 *config = _device_priv(handle->dev)->active_config;
1351 if (*config == -1) {
1352 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1359 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1361 struct linux_device_priv *priv = _device_priv(handle->dev);
1362 int fd = _device_handle_priv(handle)->fd;
1363 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1365 if (errno == EINVAL)
1366 return LIBUSB_ERROR_NOT_FOUND;
1367 else if (errno == EBUSY)
1368 return LIBUSB_ERROR_BUSY;
1369 else if (errno == ENODEV)
1370 return LIBUSB_ERROR_NO_DEVICE;
1372 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1373 return LIBUSB_ERROR_OTHER;
1376 /* update our cached active config descriptor */
1377 priv->active_config = config;
1379 return LIBUSB_SUCCESS;
1382 static int claim_interface(struct libusb_device_handle *handle, int iface)
1384 int fd = _device_handle_priv(handle)->fd;
1385 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1387 if (errno == ENOENT)
1388 return LIBUSB_ERROR_NOT_FOUND;
1389 else if (errno == EBUSY)
1390 return LIBUSB_ERROR_BUSY;
1391 else if (errno == ENODEV)
1392 return LIBUSB_ERROR_NO_DEVICE;
1394 usbi_err(HANDLE_CTX(handle),
1395 "claim interface failed, error %d errno %d", r, errno);
1396 return LIBUSB_ERROR_OTHER;
1401 static int release_interface(struct libusb_device_handle *handle, int iface)
1403 int fd = _device_handle_priv(handle)->fd;
1404 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1406 if (errno == ENODEV)
1407 return LIBUSB_ERROR_NO_DEVICE;
1409 usbi_err(HANDLE_CTX(handle),
1410 "release interface failed, error %d errno %d", r, errno);
1411 return LIBUSB_ERROR_OTHER;
1416 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1419 int fd = _device_handle_priv(handle)->fd;
1420 struct usbfs_setinterface setintf;
1423 setintf.interface = iface;
1424 setintf.altsetting = altsetting;
1425 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1427 if (errno == EINVAL)
1428 return LIBUSB_ERROR_NOT_FOUND;
1429 else if (errno == ENODEV)
1430 return LIBUSB_ERROR_NO_DEVICE;
1432 usbi_err(HANDLE_CTX(handle),
1433 "setintf failed error %d errno %d", r, errno);
1434 return LIBUSB_ERROR_OTHER;
1440 static int op_clear_halt(struct libusb_device_handle *handle,
1441 unsigned char endpoint)
1443 int fd = _device_handle_priv(handle)->fd;
1444 unsigned int _endpoint = endpoint;
1445 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1447 if (errno == ENOENT)
1448 return LIBUSB_ERROR_NOT_FOUND;
1449 else if (errno == ENODEV)
1450 return LIBUSB_ERROR_NO_DEVICE;
1452 usbi_err(HANDLE_CTX(handle),
1453 "clear_halt failed error %d errno %d", r, errno);
1454 return LIBUSB_ERROR_OTHER;
1460 static int op_reset_device(struct libusb_device_handle *handle)
1462 int fd = _device_handle_priv(handle)->fd;
1465 /* Doing a device reset will cause the usbfs driver to get unbound
1466 from any interfaces it is bound to. By voluntarily unbinding
1467 the usbfs driver ourself, we stop the kernel from rebinding
1468 the interface after reset (which would end up with the interface
1469 getting bound to the in kernel driver if any). */
1470 for (i = 0; i < USB_MAXINTERFACES; i++) {
1471 if (handle->claimed_interfaces & (1L << i)) {
1472 release_interface(handle, i);
1476 usbi_mutex_lock(&handle->lock);
1477 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1479 if (errno == ENODEV) {
1480 ret = LIBUSB_ERROR_NOT_FOUND;
1484 usbi_err(HANDLE_CTX(handle),
1485 "reset failed error %d errno %d", r, errno);
1486 ret = LIBUSB_ERROR_OTHER;
1490 /* And re-claim any interfaces which were claimed before the reset */
1491 for (i = 0; i < USB_MAXINTERFACES; i++) {
1492 if (handle->claimed_interfaces & (1L << i)) {
1494 * A driver may have completed modprobing during
1495 * IOCTL_USBFS_RESET, and bound itself as soon as
1496 * IOCTL_USBFS_RESET released the device lock
1498 r = detach_kernel_driver_and_claim(handle, i);
1500 usbi_warn(HANDLE_CTX(handle),
1501 "failed to re-claim interface %d after reset: %s",
1502 i, libusb_error_name(r));
1503 handle->claimed_interfaces &= ~(1L << i);
1504 ret = LIBUSB_ERROR_NOT_FOUND;
1509 usbi_mutex_unlock(&handle->lock);
1513 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1514 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1516 int r, fd = _device_handle_priv(handle)->fd;
1517 struct usbfs_streams *streams;
1519 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1520 return LIBUSB_ERROR_INVALID_PARAM;
1522 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1524 return LIBUSB_ERROR_NO_MEM;
1526 streams->num_streams = num_streams;
1527 streams->num_eps = num_endpoints;
1528 memcpy(streams->eps, endpoints, num_endpoints);
1530 r = ioctl(fd, req, streams);
1535 if (errno == ENOTTY)
1536 return LIBUSB_ERROR_NOT_SUPPORTED;
1537 else if (errno == EINVAL)
1538 return LIBUSB_ERROR_INVALID_PARAM;
1539 else if (errno == ENODEV)
1540 return LIBUSB_ERROR_NO_DEVICE;
1542 usbi_err(HANDLE_CTX(handle),
1543 "streams-ioctl failed error %d errno %d", r, errno);
1544 return LIBUSB_ERROR_OTHER;
1549 static int op_alloc_streams(struct libusb_device_handle *handle,
1550 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1552 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1553 num_streams, endpoints, num_endpoints);
1556 static int op_free_streams(struct libusb_device_handle *handle,
1557 unsigned char *endpoints, int num_endpoints)
1559 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1560 endpoints, num_endpoints);
1563 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1566 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1567 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1568 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1569 if (buffer == MAP_FAILED) {
1570 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1577 static int op_dev_mem_free(struct libusb_device_handle *handle,
1578 unsigned char *buffer, size_t len)
1580 if (munmap(buffer, len) != 0) {
1581 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1583 return LIBUSB_ERROR_OTHER;
1585 return LIBUSB_SUCCESS;
1589 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1592 int fd = _device_handle_priv(handle)->fd;
1593 struct usbfs_getdriver getdrv;
1596 getdrv.interface = interface;
1597 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1599 if (errno == ENODATA)
1601 else if (errno == ENODEV)
1602 return LIBUSB_ERROR_NO_DEVICE;
1604 usbi_err(HANDLE_CTX(handle),
1605 "get driver failed error %d errno %d", r, errno);
1606 return LIBUSB_ERROR_OTHER;
1609 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1612 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1615 int fd = _device_handle_priv(handle)->fd;
1616 struct usbfs_ioctl command;
1617 struct usbfs_getdriver getdrv;
1620 command.ifno = interface;
1621 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1622 command.data = NULL;
1624 getdrv.interface = interface;
1625 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1626 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1627 return LIBUSB_ERROR_NOT_FOUND;
1629 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1631 if (errno == ENODATA)
1632 return LIBUSB_ERROR_NOT_FOUND;
1633 else if (errno == EINVAL)
1634 return LIBUSB_ERROR_INVALID_PARAM;
1635 else if (errno == ENODEV)
1636 return LIBUSB_ERROR_NO_DEVICE;
1638 usbi_err(HANDLE_CTX(handle),
1639 "detach failed error %d errno %d", r, errno);
1640 return LIBUSB_ERROR_OTHER;
1646 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1649 int fd = _device_handle_priv(handle)->fd;
1650 struct usbfs_ioctl command;
1653 command.ifno = interface;
1654 command.ioctl_code = IOCTL_USBFS_CONNECT;
1655 command.data = NULL;
1657 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1659 if (errno == ENODATA)
1660 return LIBUSB_ERROR_NOT_FOUND;
1661 else if (errno == EINVAL)
1662 return LIBUSB_ERROR_INVALID_PARAM;
1663 else if (errno == ENODEV)
1664 return LIBUSB_ERROR_NO_DEVICE;
1665 else if (errno == EBUSY)
1666 return LIBUSB_ERROR_BUSY;
1668 usbi_err(HANDLE_CTX(handle),
1669 "attach failed error %d errno %d", r, errno);
1670 return LIBUSB_ERROR_OTHER;
1671 } else if (r == 0) {
1672 return LIBUSB_ERROR_NOT_FOUND;
1678 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1681 struct usbfs_disconnect_claim dc;
1682 int r, fd = _device_handle_priv(handle)->fd;
1684 dc.interface = interface;
1685 strcpy(dc.driver, "usbfs");
1686 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1687 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1688 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1694 return LIBUSB_ERROR_BUSY;
1696 return LIBUSB_ERROR_INVALID_PARAM;
1698 return LIBUSB_ERROR_NO_DEVICE;
1700 usbi_err(HANDLE_CTX(handle),
1701 "disconnect-and-claim failed errno %d", errno);
1702 return LIBUSB_ERROR_OTHER;
1705 /* Fallback code for kernels which don't support the
1706 disconnect-and-claim ioctl */
1707 r = op_detach_kernel_driver(handle, interface);
1708 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1711 return claim_interface(handle, interface);
1714 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1716 if (handle->auto_detach_kernel_driver)
1717 return detach_kernel_driver_and_claim(handle, iface);
1719 return claim_interface(handle, iface);
1722 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1726 r = release_interface(handle, iface);
1730 if (handle->auto_detach_kernel_driver)
1731 op_attach_kernel_driver(handle, iface);
1736 static void op_destroy_device(struct libusb_device *dev)
1738 struct linux_device_priv *priv = _device_priv(dev);
1739 if (priv->descriptors)
1740 free(priv->descriptors);
1741 if (priv->sysfs_dir)
1742 free(priv->sysfs_dir);
1745 /* URBs are discarded in reverse order of submission to avoid races. */
1746 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1748 struct libusb_transfer *transfer =
1749 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1750 struct linux_transfer_priv *tpriv =
1751 usbi_transfer_get_os_priv(itransfer);
1752 struct linux_device_handle_priv *dpriv =
1753 _device_handle_priv(transfer->dev_handle);
1755 struct usbfs_urb *urb;
1757 for (i = last_plus_one - 1; i >= first; i--) {
1758 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1759 urb = tpriv->iso_urbs[i];
1761 urb = &tpriv->urbs[i];
1763 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1766 if (EINVAL == errno) {
1767 usbi_dbg("URB not found --> assuming ready to be reaped");
1768 if (i == (last_plus_one - 1))
1769 ret = LIBUSB_ERROR_NOT_FOUND;
1770 } else if (ENODEV == errno) {
1771 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1772 ret = LIBUSB_ERROR_NO_DEVICE;
1774 usbi_warn(TRANSFER_CTX(transfer),
1775 "unrecognised discard errno %d", errno);
1776 ret = LIBUSB_ERROR_OTHER;
1782 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1785 for (i = 0; i < tpriv->num_urbs; i++) {
1786 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1792 free(tpriv->iso_urbs);
1793 tpriv->iso_urbs = NULL;
1796 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1798 struct libusb_transfer *transfer =
1799 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1800 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1801 struct linux_device_handle_priv *dpriv =
1802 _device_handle_priv(transfer->dev_handle);
1803 struct usbfs_urb *urbs;
1804 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1805 == LIBUSB_ENDPOINT_OUT;
1806 int bulk_buffer_len, use_bulk_continuation;
1810 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1811 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1812 return LIBUSB_ERROR_NOT_SUPPORTED;
1815 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1816 * around this by splitting large transfers into 16k blocks, and then
1817 * submit all urbs at once. it would be simpler to submit one urb at
1818 * a time, but there is a big performance gain doing it this way.
1820 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1821 * using arbritary large transfers can still be a bad idea though, as
1822 * the kernel needs to allocate physical contiguous memory for this,
1823 * which may fail for large buffers.
1825 * The kernel solves this problem by splitting the transfer into
1826 * blocks itself when the host-controller is scatter-gather capable
1827 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1829 * Last, there is the issue of short-transfers when splitting, for
1830 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1831 * is needed, but this is not always available.
1833 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1834 /* Good! Just submit everything in one go */
1835 bulk_buffer_len = transfer->length ? transfer->length : 1;
1836 use_bulk_continuation = 0;
1837 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1838 /* Split the transfers and use bulk-continuation to
1839 avoid issues with short-transfers */
1840 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1841 use_bulk_continuation = 1;
1842 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1843 /* Don't split, assume the kernel can alloc the buffer
1844 (otherwise the submit will fail with -ENOMEM) */
1845 bulk_buffer_len = transfer->length ? transfer->length : 1;
1846 use_bulk_continuation = 0;
1848 /* Bad, splitting without bulk-continuation, short transfers
1849 which end before the last urb will not work reliable! */
1850 /* Note we don't warn here as this is "normal" on kernels <
1851 2.6.32 and not a problem for most applications */
1852 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1853 use_bulk_continuation = 0;
1856 int num_urbs = transfer->length / bulk_buffer_len;
1857 int last_urb_partial = 0;
1859 if (transfer->length == 0) {
1861 } else if ((transfer->length % bulk_buffer_len) > 0) {
1862 last_urb_partial = 1;
1865 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1867 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1869 return LIBUSB_ERROR_NO_MEM;
1871 tpriv->num_urbs = num_urbs;
1872 tpriv->num_retired = 0;
1873 tpriv->reap_action = NORMAL;
1874 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1876 for (i = 0; i < num_urbs; i++) {
1877 struct usbfs_urb *urb = &urbs[i];
1878 urb->usercontext = itransfer;
1879 switch (transfer->type) {
1880 case LIBUSB_TRANSFER_TYPE_BULK:
1881 urb->type = USBFS_URB_TYPE_BULK;
1884 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1885 urb->type = USBFS_URB_TYPE_BULK;
1886 urb->stream_id = itransfer->stream_id;
1888 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1889 urb->type = USBFS_URB_TYPE_INTERRUPT;
1892 urb->endpoint = transfer->endpoint;
1893 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1894 /* don't set the short not ok flag for the last URB */
1895 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1896 urb->flags = USBFS_URB_SHORT_NOT_OK;
1897 if (i == num_urbs - 1 && last_urb_partial)
1898 urb->buffer_length = transfer->length % bulk_buffer_len;
1899 else if (transfer->length == 0)
1900 urb->buffer_length = 0;
1902 urb->buffer_length = bulk_buffer_len;
1904 if (i > 0 && use_bulk_continuation)
1905 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1907 /* we have already checked that the flag is supported */
1908 if (is_out && i == num_urbs - 1 &&
1909 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1910 urb->flags |= USBFS_URB_ZERO_PACKET;
1912 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1914 if (errno == ENODEV) {
1915 r = LIBUSB_ERROR_NO_DEVICE;
1917 usbi_err(TRANSFER_CTX(transfer),
1918 "submiturb failed error %d errno=%d", r, errno);
1919 r = LIBUSB_ERROR_IO;
1922 /* if the first URB submission fails, we can simply free up and
1923 * return failure immediately. */
1925 usbi_dbg("first URB failed, easy peasy");
1931 /* if it's not the first URB that failed, the situation is a bit
1932 * tricky. we may need to discard all previous URBs. there are
1934 * - discarding is asynchronous - discarded urbs will be reaped
1935 * later. the user must not have freed the transfer when the
1936 * discarded URBs are reaped, otherwise libusb will be using
1938 * - the earlier URBs may have completed successfully and we do
1939 * not want to throw away any data.
1940 * - this URB failing may be no error; EREMOTEIO means that
1941 * this transfer simply didn't need all the URBs we submitted
1942 * so, we report that the transfer was submitted successfully and
1943 * in case of error we discard all previous URBs. later when
1944 * the final reap completes we can report error to the user,
1945 * or success if an earlier URB was completed successfully.
1947 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1949 /* The URBs we haven't submitted yet we count as already
1951 tpriv->num_retired += num_urbs - i;
1953 /* If we completed short then don't try to discard. */
1954 if (COMPLETED_EARLY == tpriv->reap_action)
1957 discard_urbs(itransfer, 0, i);
1959 usbi_dbg("reporting successful submission but waiting for %d "
1960 "discards before reporting error", i);
1968 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1970 struct libusb_transfer *transfer =
1971 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1972 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1973 struct linux_device_handle_priv *dpriv =
1974 _device_handle_priv(transfer->dev_handle);
1975 struct usbfs_urb **urbs;
1977 int num_packets = transfer->num_iso_packets;
1979 int this_urb_len = 0;
1981 int packet_offset = 0;
1982 unsigned int packet_len;
1983 unsigned char *urb_buffer = transfer->buffer;
1985 /* usbfs places arbitrary limits on iso URBs. this limit has changed
1986 * at least three times, and it's difficult to accurately detect which
1987 * limit this running kernel might impose. so we attempt to submit
1988 * whatever the user has provided. if the kernel rejects the request
1989 * due to its size, we return an error indicating such to the user.
1992 /* calculate how many URBs we need */
1993 for (i = 0; i < num_packets; i++) {
1994 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1995 packet_len = transfer->iso_packet_desc[i].length;
1997 if (packet_len > space_remaining) {
1999 this_urb_len = packet_len;
2000 /* check that we can actually support this packet length */
2001 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2002 return LIBUSB_ERROR_INVALID_PARAM;
2004 this_urb_len += packet_len;
2007 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2009 urbs = calloc(num_urbs, sizeof(*urbs));
2011 return LIBUSB_ERROR_NO_MEM;
2013 tpriv->iso_urbs = urbs;
2014 tpriv->num_urbs = num_urbs;
2015 tpriv->num_retired = 0;
2016 tpriv->reap_action = NORMAL;
2017 tpriv->iso_packet_offset = 0;
2019 /* allocate + initialize each URB with the correct number of packets */
2020 for (i = 0; i < num_urbs; i++) {
2021 struct usbfs_urb *urb;
2022 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2023 int urb_packet_offset = 0;
2024 unsigned char *urb_buffer_orig = urb_buffer;
2028 /* swallow up all the packets we can fit into this URB */
2029 while (packet_offset < transfer->num_iso_packets) {
2030 packet_len = transfer->iso_packet_desc[packet_offset].length;
2031 if (packet_len <= space_remaining_in_urb) {
2033 urb_packet_offset++;
2035 space_remaining_in_urb -= packet_len;
2036 urb_buffer += packet_len;
2038 /* it can't fit, save it for the next URB */
2043 alloc_size = sizeof(*urb)
2044 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2045 urb = calloc(1, alloc_size);
2047 free_iso_urbs(tpriv);
2048 return LIBUSB_ERROR_NO_MEM;
2052 /* populate packet lengths */
2053 for (j = 0, k = packet_offset - urb_packet_offset;
2054 k < packet_offset; k++, j++) {
2055 packet_len = transfer->iso_packet_desc[k].length;
2056 urb->iso_frame_desc[j].length = packet_len;
2059 urb->usercontext = itransfer;
2060 urb->type = USBFS_URB_TYPE_ISO;
2061 /* FIXME: interface for non-ASAP data? */
2062 urb->flags = USBFS_URB_ISO_ASAP;
2063 urb->endpoint = transfer->endpoint;
2064 urb->number_of_packets = urb_packet_offset;
2065 urb->buffer = urb_buffer_orig;
2069 for (i = 0; i < num_urbs; i++) {
2070 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2072 if (errno == ENODEV) {
2073 r = LIBUSB_ERROR_NO_DEVICE;
2074 } else if (errno == EINVAL) {
2075 usbi_warn(TRANSFER_CTX(transfer),
2076 "submiturb failed, transfer too large");
2077 r = LIBUSB_ERROR_INVALID_PARAM;
2079 usbi_err(TRANSFER_CTX(transfer),
2080 "submiturb failed error %d errno=%d", r, errno);
2081 r = LIBUSB_ERROR_IO;
2084 /* if the first URB submission fails, we can simply free up and
2085 * return failure immediately. */
2087 usbi_dbg("first URB failed, easy peasy");
2088 free_iso_urbs(tpriv);
2092 /* if it's not the first URB that failed, the situation is a bit
2093 * tricky. we must discard all previous URBs. there are
2095 * - discarding is asynchronous - discarded urbs will be reaped
2096 * later. the user must not have freed the transfer when the
2097 * discarded URBs are reaped, otherwise libusb will be using
2099 * - the earlier URBs may have completed successfully and we do
2100 * not want to throw away any data.
2101 * so, in this case we discard all the previous URBs BUT we report
2102 * that the transfer was submitted successfully. then later when
2103 * the final discard completes we can report error to the user.
2105 tpriv->reap_action = SUBMIT_FAILED;
2107 /* The URBs we haven't submitted yet we count as already
2109 tpriv->num_retired = num_urbs - i;
2110 discard_urbs(itransfer, 0, i);
2112 usbi_dbg("reporting successful submission but waiting for %d "
2113 "discards before reporting error", i);
2121 static int submit_control_transfer(struct usbi_transfer *itransfer)
2123 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2124 struct libusb_transfer *transfer =
2125 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2126 struct linux_device_handle_priv *dpriv =
2127 _device_handle_priv(transfer->dev_handle);
2128 struct usbfs_urb *urb;
2131 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2132 return LIBUSB_ERROR_INVALID_PARAM;
2134 urb = calloc(1, sizeof(struct usbfs_urb));
2136 return LIBUSB_ERROR_NO_MEM;
2138 tpriv->num_urbs = 1;
2139 tpriv->reap_action = NORMAL;
2141 urb->usercontext = itransfer;
2142 urb->type = USBFS_URB_TYPE_CONTROL;
2143 urb->endpoint = transfer->endpoint;
2144 urb->buffer = transfer->buffer;
2145 urb->buffer_length = transfer->length;
2147 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2151 if (errno == ENODEV)
2152 return LIBUSB_ERROR_NO_DEVICE;
2154 usbi_err(TRANSFER_CTX(transfer),
2155 "submiturb failed error %d errno=%d", r, errno);
2156 return LIBUSB_ERROR_IO;
2161 static int op_submit_transfer(struct usbi_transfer *itransfer)
2163 struct libusb_transfer *transfer =
2164 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2166 switch (transfer->type) {
2167 case LIBUSB_TRANSFER_TYPE_CONTROL:
2168 return submit_control_transfer(itransfer);
2169 case LIBUSB_TRANSFER_TYPE_BULK:
2170 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2171 return submit_bulk_transfer(itransfer);
2172 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2173 return submit_bulk_transfer(itransfer);
2174 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2175 return submit_iso_transfer(itransfer);
2177 usbi_err(TRANSFER_CTX(transfer),
2178 "unknown endpoint type %d", transfer->type);
2179 return LIBUSB_ERROR_INVALID_PARAM;
2183 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2185 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2186 struct libusb_transfer *transfer =
2187 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2191 return LIBUSB_ERROR_NOT_FOUND;
2193 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2197 switch (transfer->type) {
2198 case LIBUSB_TRANSFER_TYPE_BULK:
2199 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2200 if (tpriv->reap_action == ERROR)
2202 /* else, fall through */
2204 tpriv->reap_action = CANCELLED;
2210 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2212 struct libusb_transfer *transfer =
2213 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2214 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2216 /* urbs can be freed also in submit_transfer so lock mutex first */
2217 switch (transfer->type) {
2218 case LIBUSB_TRANSFER_TYPE_CONTROL:
2219 case LIBUSB_TRANSFER_TYPE_BULK:
2220 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2221 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2227 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2228 if (tpriv->iso_urbs) {
2229 free_iso_urbs(tpriv);
2230 tpriv->iso_urbs = NULL;
2234 usbi_err(TRANSFER_CTX(transfer),
2235 "unknown endpoint type %d", transfer->type);
2239 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2240 struct usbfs_urb *urb)
2242 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2243 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2244 int urb_idx = urb - tpriv->urbs;
2246 usbi_mutex_lock(&itransfer->lock);
2247 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2248 urb_idx + 1, tpriv->num_urbs);
2250 tpriv->num_retired++;
2252 if (tpriv->reap_action != NORMAL) {
2253 /* cancelled, submit_fail, or completed early */
2254 usbi_dbg("abnormal reap: urb status %d", urb->status);
2256 /* even though we're in the process of cancelling, it's possible that
2257 * we may receive some data in these URBs that we don't want to lose.
2259 * 1. while the kernel is cancelling all the packets that make up an
2260 * URB, a few of them might complete. so we get back a successful
2261 * cancellation *and* some data.
2262 * 2. we receive a short URB which marks the early completion condition,
2263 * so we start cancelling the remaining URBs. however, we're too
2264 * slow and another URB completes (or at least completes partially).
2265 * (this can't happen since we always use BULK_CONTINUATION.)
2267 * When this happens, our objectives are not to lose any "surplus" data,
2268 * and also to stick it at the end of the previously-received data
2269 * (closing any holes), so that libusb reports the total amount of
2270 * transferred data and presents it in a contiguous chunk.
2272 if (urb->actual_length > 0) {
2273 unsigned char *target = transfer->buffer + itransfer->transferred;
2274 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2275 if (urb->buffer != target) {
2276 usbi_dbg("moving surplus data from offset %d to offset %d",
2277 (unsigned char *) urb->buffer - transfer->buffer,
2278 target - transfer->buffer);
2279 memmove(target, urb->buffer, urb->actual_length);
2281 itransfer->transferred += urb->actual_length;
2284 if (tpriv->num_retired == tpriv->num_urbs) {
2285 usbi_dbg("abnormal reap: last URB handled, reporting");
2286 if (tpriv->reap_action != COMPLETED_EARLY &&
2287 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2288 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2294 itransfer->transferred += urb->actual_length;
2296 /* Many of these errors can occur on *any* urb of a multi-urb
2297 * transfer. When they do, we tear down the rest of the transfer.
2299 switch (urb->status) {
2302 case -EREMOTEIO: /* short transfer */
2304 case -ENOENT: /* cancelled */
2309 usbi_dbg("device removed");
2310 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2311 goto cancel_remaining;
2313 usbi_dbg("detected endpoint stall");
2314 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2315 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2316 goto cancel_remaining;
2318 /* overflow can only ever occur in the last urb */
2319 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2320 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2321 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2328 usbi_dbg("low level error %d", urb->status);
2329 tpriv->reap_action = ERROR;
2330 goto cancel_remaining;
2332 usbi_warn(ITRANSFER_CTX(itransfer),
2333 "unrecognised urb status %d", urb->status);
2334 tpriv->reap_action = ERROR;
2335 goto cancel_remaining;
2338 /* if we're the last urb or we got less data than requested then we're
2340 if (urb_idx == tpriv->num_urbs - 1) {
2341 usbi_dbg("last URB in transfer --> complete!");
2343 } else if (urb->actual_length < urb->buffer_length) {
2344 usbi_dbg("short transfer %d/%d --> complete!",
2345 urb->actual_length, urb->buffer_length);
2346 if (tpriv->reap_action == NORMAL)
2347 tpriv->reap_action = COMPLETED_EARLY;
2352 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2353 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2355 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2358 /* cancel remaining urbs and wait for their completion before
2359 * reporting results */
2360 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2363 usbi_mutex_unlock(&itransfer->lock);
2369 usbi_mutex_unlock(&itransfer->lock);
2370 return CANCELLED == tpriv->reap_action ?
2371 usbi_handle_transfer_cancellation(itransfer) :
2372 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2375 static int handle_iso_completion(struct usbi_transfer *itransfer,
2376 struct usbfs_urb *urb)
2378 struct libusb_transfer *transfer =
2379 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2380 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2381 int num_urbs = tpriv->num_urbs;
2384 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2386 usbi_mutex_lock(&itransfer->lock);
2387 for (i = 0; i < num_urbs; i++) {
2388 if (urb == tpriv->iso_urbs[i]) {
2394 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2395 usbi_mutex_unlock(&itransfer->lock);
2396 return LIBUSB_ERROR_NOT_FOUND;
2399 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2402 /* copy isochronous results back in */
2404 for (i = 0; i < urb->number_of_packets; i++) {
2405 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2406 struct libusb_iso_packet_descriptor *lib_desc =
2407 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2408 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2409 switch (urb_desc->status) {
2412 case -ENOENT: /* cancelled */
2417 usbi_dbg("device removed");
2418 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2421 usbi_dbg("detected endpoint stall");
2422 lib_desc->status = LIBUSB_TRANSFER_STALL;
2425 usbi_dbg("overflow error");
2426 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2434 usbi_dbg("low-level USB error %d", urb_desc->status);
2435 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2438 usbi_warn(TRANSFER_CTX(transfer),
2439 "unrecognised urb status %d", urb_desc->status);
2440 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2443 lib_desc->actual_length = urb_desc->actual_length;
2446 tpriv->num_retired++;
2448 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2449 usbi_dbg("CANCEL: urb status %d", urb->status);
2451 if (tpriv->num_retired == num_urbs) {
2452 usbi_dbg("CANCEL: last URB handled, reporting");
2453 free_iso_urbs(tpriv);
2454 if (tpriv->reap_action == CANCELLED) {
2455 usbi_mutex_unlock(&itransfer->lock);
2456 return usbi_handle_transfer_cancellation(itransfer);
2458 usbi_mutex_unlock(&itransfer->lock);
2459 return usbi_handle_transfer_completion(itransfer,
2460 LIBUSB_TRANSFER_ERROR);
2466 switch (urb->status) {
2469 case -ENOENT: /* cancelled */
2473 usbi_dbg("device removed");
2474 status = LIBUSB_TRANSFER_NO_DEVICE;
2477 usbi_warn(TRANSFER_CTX(transfer),
2478 "unrecognised urb status %d", urb->status);
2479 status = LIBUSB_TRANSFER_ERROR;
2483 /* if we're the last urb then we're done */
2484 if (urb_idx == num_urbs) {
2485 usbi_dbg("last URB in transfer --> complete!");
2486 free_iso_urbs(tpriv);
2487 usbi_mutex_unlock(&itransfer->lock);
2488 return usbi_handle_transfer_completion(itransfer, status);
2492 usbi_mutex_unlock(&itransfer->lock);
2496 static int handle_control_completion(struct usbi_transfer *itransfer,
2497 struct usbfs_urb *urb)
2499 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2502 usbi_mutex_lock(&itransfer->lock);
2503 usbi_dbg("handling completion status %d", urb->status);
2505 itransfer->transferred += urb->actual_length;
2507 if (tpriv->reap_action == CANCELLED) {
2508 if (urb->status != 0 && urb->status != -ENOENT)
2509 usbi_warn(ITRANSFER_CTX(itransfer),
2510 "cancel: unrecognised urb status %d", urb->status);
2513 usbi_mutex_unlock(&itransfer->lock);
2514 return usbi_handle_transfer_cancellation(itransfer);
2517 switch (urb->status) {
2519 status = LIBUSB_TRANSFER_COMPLETED;
2521 case -ENOENT: /* cancelled */
2522 status = LIBUSB_TRANSFER_CANCELLED;
2526 usbi_dbg("device removed");
2527 status = LIBUSB_TRANSFER_NO_DEVICE;
2530 usbi_dbg("unsupported control request");
2531 status = LIBUSB_TRANSFER_STALL;
2534 usbi_dbg("control overflow error");
2535 status = LIBUSB_TRANSFER_OVERFLOW;
2542 usbi_dbg("low-level bus error occurred");
2543 status = LIBUSB_TRANSFER_ERROR;
2546 usbi_warn(ITRANSFER_CTX(itransfer),
2547 "unrecognised urb status %d", urb->status);
2548 status = LIBUSB_TRANSFER_ERROR;
2554 usbi_mutex_unlock(&itransfer->lock);
2555 return usbi_handle_transfer_completion(itransfer, status);
2558 static int reap_for_handle(struct libusb_device_handle *handle)
2560 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2562 struct usbfs_urb *urb;
2563 struct usbi_transfer *itransfer;
2564 struct libusb_transfer *transfer;
2566 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2567 if (r == -1 && errno == EAGAIN)
2570 if (errno == ENODEV)
2571 return LIBUSB_ERROR_NO_DEVICE;
2573 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2575 return LIBUSB_ERROR_IO;
2578 itransfer = urb->usercontext;
2579 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2581 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2582 urb->actual_length);
2584 switch (transfer->type) {
2585 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2586 return handle_iso_completion(itransfer, urb);
2587 case LIBUSB_TRANSFER_TYPE_BULK:
2588 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2589 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2590 return handle_bulk_completion(itransfer, urb);
2591 case LIBUSB_TRANSFER_TYPE_CONTROL:
2592 return handle_control_completion(itransfer, urb);
2594 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2596 return LIBUSB_ERROR_OTHER;
2600 static int op_handle_events(struct libusb_context *ctx,
2601 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2606 usbi_mutex_lock(&ctx->open_devs_lock);
2607 for (i = 0; i < nfds && num_ready > 0; i++) {
2608 struct pollfd *pollfd = &fds[i];
2609 struct libusb_device_handle *handle;
2610 struct linux_device_handle_priv *hpriv = NULL;
2612 if (!pollfd->revents)
2616 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2617 hpriv = _device_handle_priv(handle);
2618 if (hpriv->fd == pollfd->fd)
2622 if (!hpriv || hpriv->fd != pollfd->fd) {
2623 usbi_err(ctx, "cannot find handle for fd %d",
2628 if (pollfd->revents & POLLERR) {
2629 /* remove the fd from the pollfd set so that it doesn't continuously
2630 * trigger an event, and flag that it has been removed so op_close()
2631 * doesn't try to remove it a second time */
2632 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2633 hpriv->fd_removed = 1;
2635 /* device will still be marked as attached if hotplug monitor thread
2636 * hasn't processed remove event yet */
2637 usbi_mutex_static_lock(&linux_hotplug_lock);
2638 if (handle->dev->attached)
2639 linux_device_disconnected(handle->dev->bus_number,
2640 handle->dev->device_address);
2641 usbi_mutex_static_unlock(&linux_hotplug_lock);
2643 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2645 r = reap_for_handle(handle);
2649 usbi_handle_disconnect(handle);
2654 r = reap_for_handle(handle);
2656 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2664 usbi_mutex_unlock(&ctx->open_devs_lock);
2668 static int op_clock_gettime(int clk_id, struct timespec *tp)
2671 case USBI_CLOCK_MONOTONIC:
2672 return clock_gettime(monotonic_clkid, tp);
2673 case USBI_CLOCK_REALTIME:
2674 return clock_gettime(CLOCK_REALTIME, tp);
2676 return LIBUSB_ERROR_INVALID_PARAM;
2680 #ifdef USBI_TIMERFD_AVAILABLE
2681 static clockid_t op_get_timerfd_clockid(void)
2683 return monotonic_clkid;
2688 const struct usbi_os_backend linux_usbfs_backend = {
2689 .name = "Linux usbfs",
2690 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2693 .get_device_list = NULL,
2694 .hotplug_poll = op_hotplug_poll,
2695 .get_device_descriptor = op_get_device_descriptor,
2696 .get_active_config_descriptor = op_get_active_config_descriptor,
2697 .get_config_descriptor = op_get_config_descriptor,
2698 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2702 .get_configuration = op_get_configuration,
2703 .set_configuration = op_set_configuration,
2704 .claim_interface = op_claim_interface,
2705 .release_interface = op_release_interface,
2707 .set_interface_altsetting = op_set_interface,
2708 .clear_halt = op_clear_halt,
2709 .reset_device = op_reset_device,
2711 .alloc_streams = op_alloc_streams,
2712 .free_streams = op_free_streams,
2714 .dev_mem_alloc = op_dev_mem_alloc,
2715 .dev_mem_free = op_dev_mem_free,
2717 .kernel_driver_active = op_kernel_driver_active,
2718 .detach_kernel_driver = op_detach_kernel_driver,
2719 .attach_kernel_driver = op_attach_kernel_driver,
2721 .destroy_device = op_destroy_device,
2723 .submit_transfer = op_submit_transfer,
2724 .cancel_transfer = op_cancel_transfer,
2725 .clear_transfer_priv = op_clear_transfer_priv,
2727 .handle_events = op_handle_events,
2729 .clock_gettime = op_clock_gettime,
2731 #ifdef USBI_TIMERFD_AVAILABLE
2732 .get_timerfd_clockid = op_get_timerfd_clockid,
2735 .device_priv_size = sizeof(struct linux_device_priv),
2736 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2737 .transfer_priv_size = sizeof(struct linux_transfer_priv),