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.23 adds support for O_CLOEXEC when opening files, which marks the
85 * close-on-exec flag in the underlying file descriptor. */
86 static int supports_flag_cloexec = -1;
88 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
89 * allows us to mark URBs as being part of a specific logical transfer when
90 * we submit them to the kernel. then, on any error except a cancellation, all
91 * URBs within that transfer will be cancelled and no more URBs will be
92 * accepted for the transfer, meaning that no more data can creep in.
94 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
95 * (in either direction) except the first.
96 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
97 * last; it means that the kernel should treat a short reply as an error.
98 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
99 * transfers can't be short unless there's already some sort of error), and
100 * setting this flag is disallowed (a kernel with USB debugging enabled will
103 static int supports_flag_bulk_continuation = -1;
105 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
106 * allows us to mark URBs that should be followed by a zero length data
107 * packet, which can be required by device- or class-specific protocols.
109 static int supports_flag_zero_packet = -1;
111 /* clock ID for monotonic clock, as not all clock sources are available on all
112 * systems. appropriate choice made at initialization time. */
113 static clockid_t monotonic_clkid = -1;
115 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
116 * to sysfs, so we can relate devices. This also implies that we can read
117 * the active configuration through bConfigurationValue */
118 static int sysfs_can_relate_devices = -1;
120 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
121 * config descriptors (rather then just the active config) to the sysfs
122 * descriptors file, so from then on we can use them. */
123 static int sysfs_has_descriptors = -1;
125 /* how many times have we initted (and not exited) ? */
126 static int init_count = 0;
128 /* Serialize hotplug start/stop */
129 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
130 /* Serialize scan-devices, event-thread, and poll */
131 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
133 static int linux_start_event_monitor(void);
134 static int linux_stop_event_monitor(void);
135 static int linux_scan_devices(struct libusb_context *ctx);
136 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
137 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
139 #if !defined(USE_UDEV)
140 static int linux_default_scan_devices (struct libusb_context *ctx);
143 struct linux_device_priv {
145 unsigned char *descriptors;
147 int active_config; /* cache val for !sysfs_can_relate_devices */
150 struct linux_device_handle_priv {
158 /* submission failed after the first URB, so await cancellation/completion
159 * of all the others */
162 /* cancelled by user or timeout */
165 /* completed multi-URB transfer in non-final URB */
168 /* one or more urbs encountered a low-level error */
172 struct linux_transfer_priv {
174 struct usbfs_urb *urbs;
175 struct usbfs_urb **iso_urbs;
178 enum reap_action reap_action;
181 enum libusb_transfer_status reap_status;
183 /* next iso packet in user-supplied transfer to be populated */
184 int iso_packet_offset;
187 static int _open(const char *path, int flags)
189 #if defined(O_CLOEXEC)
190 if (supports_flag_cloexec)
191 return open(path, flags | O_CLOEXEC);
194 return open(path, flags);
197 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
199 struct libusb_context *ctx = DEVICE_CTX(dev);
205 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
206 usbfs_path, dev->bus_number, dev->device_address);
208 snprintf(path, PATH_MAX, "%s/%03d/%03d",
209 usbfs_path, dev->bus_number, dev->device_address);
211 fd = _open(path, mode);
213 return fd; /* Success */
215 if (errno == ENOENT) {
217 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
219 /* Wait 10ms for USB device path creation.*/
220 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
222 fd = _open(path, mode);
224 return fd; /* Success */
228 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
229 path, strerror(errno));
230 if (errno == EACCES && mode == O_RDWR)
231 usbi_err(ctx, "libusb requires write access to USB "
236 return LIBUSB_ERROR_ACCESS;
238 return LIBUSB_ERROR_NO_DEVICE;
239 return LIBUSB_ERROR_IO;
242 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
244 return (struct linux_device_priv *) dev->os_priv;
247 static struct linux_device_handle_priv *_device_handle_priv(
248 struct libusb_device_handle *handle)
250 return (struct linux_device_handle_priv *) handle->os_priv;
253 /* check dirent for a /dev/usbdev%d.%d name
254 * optionally return bus/device on success */
255 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
259 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
262 usbi_dbg("found: %s", entry->d_name);
270 static int check_usb_vfs(const char *dirname)
273 struct dirent *entry;
276 dir = opendir(dirname);
280 while ((entry = readdir(dir)) != NULL) {
281 if (entry->d_name[0] == '.')
284 /* We assume if we find any files that it must be the right place */
293 static const char *find_usbfs_path(void)
295 const char *path = "/dev/bus/usb";
296 const char *ret = NULL;
298 if (check_usb_vfs(path)) {
301 path = "/proc/bus/usb";
302 if (check_usb_vfs(path))
306 /* look for /dev/usbdev*.* if the normal places fail */
308 struct dirent *entry;
314 while ((entry = readdir(dir)) != NULL) {
315 if (_is_usbdev_entry(entry, NULL, NULL)) {
316 /* found one; that's enough */
326 /* On udev based systems without any usb-devices /dev/bus/usb will not
327 * exist. So if we've not found anything and we're using udev for hotplug
328 * simply assume /dev/bus/usb rather then making libusb_init fail. */
329 #if defined(USE_UDEV)
331 ret = "/dev/bus/usb";
335 usbi_dbg("found usbfs at %s", ret);
340 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
341 * seem to lack it). fall back to REALTIME if we have to. */
342 static clockid_t find_monotonic_clock(void)
344 #ifdef CLOCK_MONOTONIC
348 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
349 * because it's not available through timerfd */
350 r = clock_gettime(CLOCK_MONOTONIC, &ts);
352 return CLOCK_MONOTONIC;
353 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
356 return CLOCK_REALTIME;
359 static int kernel_version_ge(int major, int minor, int sublevel)
362 int atoms, kmajor, kminor, ksublevel;
366 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
375 /* kmajor == major */
377 return 0 == minor && 0 == sublevel;
383 /* kminor == minor */
385 return 0 == sublevel;
387 return ksublevel >= sublevel;
390 static int op_init(struct libusb_context *ctx)
395 usbfs_path = find_usbfs_path();
397 usbi_err(ctx, "could not find usbfs");
398 return LIBUSB_ERROR_OTHER;
401 if (monotonic_clkid == -1)
402 monotonic_clkid = find_monotonic_clock();
404 if (supports_flag_cloexec == -1) {
405 /* O_CLOEXEC flag available from Linux 2.6.23 */
406 supports_flag_cloexec = kernel_version_ge(2,6,23);
407 if (supports_flag_cloexec == -1) {
408 usbi_err(ctx, "error checking for O_CLOEXEC support");
409 return LIBUSB_ERROR_OTHER;
413 if (supports_flag_bulk_continuation == -1) {
414 /* bulk continuation URB flag available from Linux 2.6.32 */
415 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
416 if (supports_flag_bulk_continuation == -1) {
417 usbi_err(ctx, "error checking for bulk continuation support");
418 return LIBUSB_ERROR_OTHER;
422 if (supports_flag_bulk_continuation)
423 usbi_dbg("bulk continuation flag supported");
425 if (-1 == supports_flag_zero_packet) {
426 /* zero length packet URB flag fixed since Linux 2.6.31 */
427 supports_flag_zero_packet = kernel_version_ge(2,6,31);
428 if (-1 == supports_flag_zero_packet) {
429 usbi_err(ctx, "error checking for zero length packet support");
430 return LIBUSB_ERROR_OTHER;
434 if (supports_flag_zero_packet)
435 usbi_dbg("zero length packet flag supported");
437 if (-1 == sysfs_has_descriptors) {
438 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
439 sysfs_has_descriptors = kernel_version_ge(2,6,26);
440 if (-1 == sysfs_has_descriptors) {
441 usbi_err(ctx, "error checking for sysfs descriptors");
442 return LIBUSB_ERROR_OTHER;
446 if (-1 == sysfs_can_relate_devices) {
447 /* sysfs has busnum since Linux 2.6.22 */
448 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
449 if (-1 == sysfs_can_relate_devices) {
450 usbi_err(ctx, "error checking for sysfs busnum");
451 return LIBUSB_ERROR_OTHER;
455 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
456 r = stat(SYSFS_DEVICE_PATH, &statbuf);
457 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
458 usbi_warn(ctx, "sysfs not mounted");
459 sysfs_can_relate_devices = 0;
460 sysfs_has_descriptors = 0;
464 if (sysfs_can_relate_devices)
465 usbi_dbg("sysfs can relate devices");
467 if (sysfs_has_descriptors)
468 usbi_dbg("sysfs has complete descriptors");
470 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
472 if (init_count == 0) {
473 /* start up hotplug event handler */
474 r = linux_start_event_monitor();
476 if (r == LIBUSB_SUCCESS) {
477 r = linux_scan_devices(ctx);
478 if (r == LIBUSB_SUCCESS)
480 else if (init_count == 0)
481 linux_stop_event_monitor();
483 usbi_err(ctx, "error starting hotplug event monitor");
484 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
489 static void op_exit(struct libusb_context *ctx)
492 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
493 assert(init_count != 0);
495 /* tear down event handler */
496 (void)linux_stop_event_monitor();
498 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
501 static int linux_start_event_monitor(void)
503 #if defined(USE_UDEV)
504 return linux_udev_start_event_monitor();
506 return linux_netlink_start_event_monitor();
510 static int linux_stop_event_monitor(void)
512 #if defined(USE_UDEV)
513 return linux_udev_stop_event_monitor();
515 return linux_netlink_stop_event_monitor();
519 static int linux_scan_devices(struct libusb_context *ctx)
523 usbi_mutex_static_lock(&linux_hotplug_lock);
525 #if defined(USE_UDEV)
526 ret = linux_udev_scan_devices(ctx);
528 ret = linux_default_scan_devices(ctx);
531 usbi_mutex_static_unlock(&linux_hotplug_lock);
536 static void op_hotplug_poll(void)
538 #if defined(USE_UDEV)
539 linux_udev_hotplug_poll();
541 linux_netlink_hotplug_poll();
545 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
547 struct linux_device_priv *priv = _device_priv(dev);
548 char filename[PATH_MAX];
551 snprintf(filename, PATH_MAX, "%s/%s/%s",
552 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
553 fd = _open(filename, O_RDONLY);
555 usbi_err(DEVICE_CTX(dev),
556 "open %s failed ret=%d errno=%d", filename, fd, errno);
557 return LIBUSB_ERROR_IO;
563 /* Note only suitable for attributes which always read >= 0, < 0 is error */
564 static int __read_sysfs_attr(struct libusb_context *ctx,
565 const char *devname, const char *attr)
567 char filename[PATH_MAX];
571 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
573 fd = _open(filename, O_RDONLY);
575 if (errno == ENOENT) {
576 /* File doesn't exist. Assume the device has been
577 disconnected (see trac ticket #70). */
578 return LIBUSB_ERROR_NO_DEVICE;
580 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
581 return LIBUSB_ERROR_IO;
586 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
588 return LIBUSB_ERROR_OTHER;
591 r = fscanf(f, "%d", &value);
594 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
595 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
598 usbi_err(ctx, "%s contains a negative value", filename);
599 return LIBUSB_ERROR_IO;
605 static int op_get_device_descriptor(struct libusb_device *dev,
606 unsigned char *buffer, int *host_endian)
608 struct linux_device_priv *priv = _device_priv(dev);
610 *host_endian = sysfs_has_descriptors ? 0 : 1;
611 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
616 /* read the bConfigurationValue for a device */
617 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
620 char tmp[5] = {0, 0, 0, 0, 0};
625 fd = _open_sysfs_attr(dev, "bConfigurationValue");
629 r = read(fd, tmp, sizeof(tmp));
632 usbi_err(DEVICE_CTX(dev),
633 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
634 return LIBUSB_ERROR_IO;
636 usbi_dbg("device unconfigured");
641 if (tmp[sizeof(tmp) - 1] != 0) {
642 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
643 return LIBUSB_ERROR_IO;
644 } else if (tmp[0] == 0) {
645 usbi_err(DEVICE_CTX(dev), "no configuration value?");
646 return LIBUSB_ERROR_IO;
649 num = strtol(tmp, &endptr, 10);
651 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
652 return LIBUSB_ERROR_IO;
659 int linux_get_device_address (struct libusb_context *ctx, int detached,
660 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
661 const char *sys_name)
665 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
666 /* can't use sysfs to read the bus and device number if the
667 * device has been detached */
668 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
669 if (NULL == dev_node) {
670 return LIBUSB_ERROR_OTHER;
673 /* will this work with all supported kernel versions? */
674 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
675 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
676 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
677 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
680 return LIBUSB_SUCCESS;
683 usbi_dbg("scan %s", sys_name);
685 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
688 if (sysfs_attr > 255)
689 return LIBUSB_ERROR_INVALID_PARAM;
690 *busnum = (uint8_t) sysfs_attr;
692 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
695 if (sysfs_attr > 255)
696 return LIBUSB_ERROR_INVALID_PARAM;
698 *devaddr = (uint8_t) sysfs_attr;
700 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
702 return LIBUSB_SUCCESS;
705 /* Return offset of the next descriptor with the given type */
706 static int seek_to_next_descriptor(struct libusb_context *ctx,
707 uint8_t descriptor_type, unsigned char *buffer, int size)
709 struct usb_descriptor_header header;
712 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
714 return LIBUSB_ERROR_NOT_FOUND;
717 usbi_err(ctx, "short descriptor read %d/2", size);
718 return LIBUSB_ERROR_IO;
720 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
722 if (i && header.bDescriptorType == descriptor_type)
725 usbi_err(ctx, "bLength overflow by %d bytes", -size);
726 return LIBUSB_ERROR_IO;
729 /* Return offset to next config */
730 static int seek_to_next_config(struct libusb_context *ctx,
731 unsigned char *buffer, int size)
733 struct libusb_config_descriptor config;
736 return LIBUSB_ERROR_NOT_FOUND;
738 if (size < LIBUSB_DT_CONFIG_SIZE) {
739 usbi_err(ctx, "short descriptor read %d/%d",
740 size, LIBUSB_DT_CONFIG_SIZE);
741 return LIBUSB_ERROR_IO;
744 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
745 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
746 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
747 config.bDescriptorType);
748 return LIBUSB_ERROR_IO;
752 * In usbfs the config descriptors are config.wTotalLength bytes apart,
753 * with any short reads from the device appearing as holes in the file.
755 * In sysfs wTotalLength is ignored, instead the kernel returns a
756 * config descriptor with verified bLength fields, with descriptors
757 * with an invalid bLength removed.
759 if (sysfs_has_descriptors) {
760 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
762 if (next == LIBUSB_ERROR_NOT_FOUND)
767 if (next != config.wTotalLength)
768 usbi_warn(ctx, "config length mismatch wTotalLength "
769 "%d real %d", config.wTotalLength, next);
772 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
773 usbi_err(ctx, "invalid wTotalLength %d",
774 config.wTotalLength);
775 return LIBUSB_ERROR_IO;
776 } else if (config.wTotalLength > size) {
777 usbi_warn(ctx, "short descriptor read %d/%d",
778 size, config.wTotalLength);
781 return config.wTotalLength;
785 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
786 uint8_t value, unsigned char **buffer, int *host_endian)
788 struct libusb_context *ctx = DEVICE_CTX(dev);
789 struct linux_device_priv *priv = _device_priv(dev);
790 unsigned char *descriptors = priv->descriptors;
791 int size = priv->descriptors_len;
792 struct libusb_config_descriptor *config;
795 /* Unlike the device desc. config descs. are always in raw format */
798 /* Skip device header */
799 descriptors += DEVICE_DESC_LENGTH;
800 size -= DEVICE_DESC_LENGTH;
802 /* Seek till the config is found, or till "EOF" */
804 int next = seek_to_next_config(ctx, descriptors, size);
807 config = (struct libusb_config_descriptor *)descriptors;
808 if (config->bConfigurationValue == value) {
809 *buffer = descriptors;
817 static int op_get_active_config_descriptor(struct libusb_device *dev,
818 unsigned char *buffer, size_t len, int *host_endian)
821 unsigned char *config_desc;
823 if (sysfs_can_relate_devices) {
824 r = sysfs_get_active_config(dev, &config);
828 /* Use cached bConfigurationValue */
829 struct linux_device_priv *priv = _device_priv(dev);
830 config = priv->active_config;
833 return LIBUSB_ERROR_NOT_FOUND;
835 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
840 len = MIN(len, (size_t)r);
841 memcpy(buffer, config_desc, len);
845 static int op_get_config_descriptor(struct libusb_device *dev,
846 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
848 struct linux_device_priv *priv = _device_priv(dev);
849 unsigned char *descriptors = priv->descriptors;
850 int i, r, size = priv->descriptors_len;
852 /* Unlike the device desc. config descs. are always in raw format */
855 /* Skip device header */
856 descriptors += DEVICE_DESC_LENGTH;
857 size -= DEVICE_DESC_LENGTH;
859 /* Seek till the config is found, or till "EOF" */
861 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
864 if (i == config_index)
870 len = MIN(len, (size_t)r);
871 memcpy(buffer, descriptors, len);
875 /* send a control message to retrieve active configuration */
876 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
878 struct linux_device_priv *priv = _device_priv(dev);
879 unsigned char active_config = 0;
882 struct usbfs_ctrltransfer ctrl = {
883 .bmRequestType = LIBUSB_ENDPOINT_IN,
884 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
889 .data = &active_config
892 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
895 return LIBUSB_ERROR_NO_DEVICE;
897 /* we hit this error path frequently with buggy devices :( */
898 usbi_warn(DEVICE_CTX(dev),
899 "get_configuration failed ret=%d errno=%d", r, errno);
900 priv->active_config = -1;
902 if (active_config > 0) {
903 priv->active_config = active_config;
905 /* some buggy devices have a configuration 0, but we're
906 * reaching into the corner of a corner case here, so let's
907 * not support buggy devices in these circumstances.
908 * stick to the specs: a configuration value of 0 means
910 usbi_warn(DEVICE_CTX(dev),
911 "active cfg 0? assuming unconfigured device");
912 priv->active_config = -1;
916 return LIBUSB_SUCCESS;
919 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
920 uint8_t devaddr, const char *sysfs_dir)
922 struct linux_device_priv *priv = _device_priv(dev);
923 struct libusb_context *ctx = DEVICE_CTX(dev);
924 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
928 dev->bus_number = busnum;
929 dev->device_address = devaddr;
932 priv->sysfs_dir = strdup(sysfs_dir);
933 if (!priv->sysfs_dir)
934 return LIBUSB_ERROR_NO_MEM;
936 /* Note speed can contain 1.5, in this case __read_sysfs_attr
937 will stop parsing at the '.' and return 1 */
938 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
941 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
942 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
943 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
944 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
946 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
951 /* cache descriptors in memory */
952 if (sysfs_has_descriptors)
953 fd = _open_sysfs_attr(dev, "descriptors");
955 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
960 descriptors_size *= 2;
961 priv->descriptors = usbi_reallocf(priv->descriptors,
963 if (!priv->descriptors) {
965 return LIBUSB_ERROR_NO_MEM;
967 /* usbfs has holes in the file */
968 if (!sysfs_has_descriptors) {
969 memset(priv->descriptors + priv->descriptors_len,
970 0, descriptors_size - priv->descriptors_len);
972 r = read(fd, priv->descriptors + priv->descriptors_len,
973 descriptors_size - priv->descriptors_len);
975 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
978 return LIBUSB_ERROR_IO;
980 priv->descriptors_len += r;
981 } while (priv->descriptors_len == descriptors_size);
985 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
986 usbi_err(ctx, "short descriptor read (%d)",
987 priv->descriptors_len);
988 return LIBUSB_ERROR_IO;
991 if (sysfs_can_relate_devices)
992 return LIBUSB_SUCCESS;
994 /* cache active config */
995 fd = _get_usbfs_fd(dev, O_RDWR, 1);
997 /* cannot send a control message to determine the active
998 * config. just assume the first one is active. */
999 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1000 "active configuration descriptor");
1001 if (priv->descriptors_len >=
1002 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1003 struct libusb_config_descriptor config;
1004 usbi_parse_descriptor(
1005 priv->descriptors + DEVICE_DESC_LENGTH,
1006 "bbwbbbbb", &config, 0);
1007 priv->active_config = config.bConfigurationValue;
1009 priv->active_config = -1; /* No config dt */
1011 return LIBUSB_SUCCESS;
1014 r = usbfs_get_active_config(dev, fd);
1020 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1022 struct libusb_context *ctx = DEVICE_CTX(dev);
1023 struct libusb_device *it;
1024 char *parent_sysfs_dir, *tmp;
1025 int ret, add_parent = 1;
1027 /* XXX -- can we figure out the topology when using usbfs? */
1028 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1029 /* either using usbfs or finding the parent of a root hub */
1030 return LIBUSB_SUCCESS;
1033 parent_sysfs_dir = strdup(sysfs_dir);
1034 if (NULL == parent_sysfs_dir) {
1035 return LIBUSB_ERROR_NO_MEM;
1037 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1038 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1039 dev->port_number = atoi(tmp + 1);
1042 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1044 free (parent_sysfs_dir);
1045 return LIBUSB_SUCCESS;
1048 /* is the parent a root hub? */
1049 if (NULL == strchr(parent_sysfs_dir, '-')) {
1050 tmp = parent_sysfs_dir;
1051 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1054 return LIBUSB_ERROR_NO_MEM;
1059 /* find the parent in the context */
1060 usbi_mutex_lock(&ctx->usb_devs_lock);
1061 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1062 struct linux_device_priv *priv = _device_priv(it);
1063 if (priv->sysfs_dir) {
1064 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1065 dev->parent_dev = libusb_ref_device(it);
1070 usbi_mutex_unlock(&ctx->usb_devs_lock);
1072 if (!dev->parent_dev && add_parent) {
1073 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1075 sysfs_scan_device(ctx, parent_sysfs_dir);
1080 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1081 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1083 free (parent_sysfs_dir);
1085 return LIBUSB_SUCCESS;
1088 int linux_enumerate_device(struct libusb_context *ctx,
1089 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1091 unsigned long session_id;
1092 struct libusb_device *dev;
1095 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1096 * will be reused. instead we should add a simple sysfs attribute with
1098 session_id = busnum << 8 | devaddr;
1099 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1102 dev = usbi_get_device_by_session_id(ctx, session_id);
1104 /* device already exists in the context */
1105 usbi_dbg("session_id %ld already exists", session_id);
1106 libusb_unref_device(dev);
1107 return LIBUSB_SUCCESS;
1110 usbi_dbg("allocating new device for %d/%d (session %ld)",
1111 busnum, devaddr, session_id);
1112 dev = usbi_alloc_device(ctx, session_id);
1114 return LIBUSB_ERROR_NO_MEM;
1116 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1119 r = usbi_sanitize_device(dev);
1123 r = linux_get_parent_info(dev, sysfs_dir);
1128 libusb_unref_device(dev);
1130 usbi_connect_device(dev);
1135 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1137 struct libusb_context *ctx;
1139 usbi_mutex_static_lock(&active_contexts_lock);
1140 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1141 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1143 usbi_mutex_static_unlock(&active_contexts_lock);
1146 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1148 struct libusb_context *ctx;
1149 struct libusb_device *dev;
1150 unsigned long session_id = busnum << 8 | devaddr;
1152 usbi_mutex_static_lock(&active_contexts_lock);
1153 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1154 dev = usbi_get_device_by_session_id (ctx, session_id);
1156 usbi_disconnect_device (dev);
1157 libusb_unref_device(dev);
1159 usbi_dbg("device not found for session %x", session_id);
1162 usbi_mutex_static_unlock(&active_contexts_lock);
1165 #if !defined(USE_UDEV)
1166 /* open a bus directory and adds all discovered devices to the context */
1167 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1170 char dirpath[PATH_MAX];
1171 struct dirent *entry;
1172 int r = LIBUSB_ERROR_IO;
1174 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1175 usbi_dbg("%s", dirpath);
1176 dir = opendir(dirpath);
1178 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1179 /* FIXME: should handle valid race conditions like hub unplugged
1180 * during directory iteration - this is not an error */
1184 while ((entry = readdir(dir))) {
1187 if (entry->d_name[0] == '.')
1190 devaddr = atoi(entry->d_name);
1192 usbi_dbg("unknown dir entry %s", entry->d_name);
1196 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1197 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1208 static int usbfs_get_device_list(struct libusb_context *ctx)
1210 struct dirent *entry;
1211 DIR *buses = opendir(usbfs_path);
1215 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1216 return LIBUSB_ERROR_IO;
1219 while ((entry = readdir(buses))) {
1222 if (entry->d_name[0] == '.')
1227 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1230 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1232 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1236 busnum = atoi(entry->d_name);
1238 usbi_dbg("unknown dir entry %s", entry->d_name);
1242 r = usbfs_scan_busdir(ctx, busnum);
1254 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1256 uint8_t busnum, devaddr;
1259 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1260 if (LIBUSB_SUCCESS != ret) {
1264 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1268 #if !defined(USE_UDEV)
1269 static int sysfs_get_device_list(struct libusb_context *ctx)
1271 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1272 struct dirent *entry;
1273 int r = LIBUSB_ERROR_IO;
1276 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1280 while ((entry = readdir(devices))) {
1281 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1282 || strchr(entry->d_name, ':'))
1285 if (sysfs_scan_device(ctx, entry->d_name)) {
1286 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1297 static int linux_default_scan_devices (struct libusb_context *ctx)
1299 /* we can retrieve device list and descriptors from sysfs or usbfs.
1300 * sysfs is preferable, because if we use usbfs we end up resuming
1301 * any autosuspended USB devices. however, sysfs is not available
1302 * everywhere, so we need a usbfs fallback too.
1304 * as described in the "sysfs vs usbfs" comment at the top of this
1305 * file, sometimes we have sysfs but not enough information to
1306 * relate sysfs devices to usbfs nodes. op_init() determines the
1307 * adequacy of sysfs and sets sysfs_can_relate_devices.
1309 if (sysfs_can_relate_devices != 0)
1310 return sysfs_get_device_list(ctx);
1312 return usbfs_get_device_list(ctx);
1316 static int op_open(struct libusb_device_handle *handle)
1318 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1321 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1322 if (hpriv->fd < 0) {
1323 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1324 /* device will still be marked as attached if hotplug monitor thread
1325 * hasn't processed remove event yet */
1326 usbi_mutex_static_lock(&linux_hotplug_lock);
1327 if (handle->dev->attached) {
1328 usbi_dbg("open failed with no device, but device still attached");
1329 linux_device_disconnected(handle->dev->bus_number,
1330 handle->dev->device_address);
1332 usbi_mutex_static_unlock(&linux_hotplug_lock);
1337 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1339 if (errno == ENOTTY)
1340 usbi_dbg("getcap not available");
1342 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1344 if (supports_flag_zero_packet)
1345 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1346 if (supports_flag_bulk_continuation)
1347 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1350 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1357 static void op_close(struct libusb_device_handle *dev_handle)
1359 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1360 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1361 if (!hpriv->fd_removed)
1362 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1366 static int op_get_configuration(struct libusb_device_handle *handle,
1371 if (sysfs_can_relate_devices) {
1372 r = sysfs_get_active_config(handle->dev, config);
1374 r = usbfs_get_active_config(handle->dev,
1375 _device_handle_priv(handle)->fd);
1376 if (r == LIBUSB_SUCCESS)
1377 *config = _device_priv(handle->dev)->active_config;
1382 if (*config == -1) {
1383 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1390 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1392 struct linux_device_priv *priv = _device_priv(handle->dev);
1393 int fd = _device_handle_priv(handle)->fd;
1394 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1396 if (errno == EINVAL)
1397 return LIBUSB_ERROR_NOT_FOUND;
1398 else if (errno == EBUSY)
1399 return LIBUSB_ERROR_BUSY;
1400 else if (errno == ENODEV)
1401 return LIBUSB_ERROR_NO_DEVICE;
1403 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1404 return LIBUSB_ERROR_OTHER;
1407 /* update our cached active config descriptor */
1408 priv->active_config = config;
1410 return LIBUSB_SUCCESS;
1413 static int claim_interface(struct libusb_device_handle *handle, int iface)
1415 int fd = _device_handle_priv(handle)->fd;
1416 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1418 if (errno == ENOENT)
1419 return LIBUSB_ERROR_NOT_FOUND;
1420 else if (errno == EBUSY)
1421 return LIBUSB_ERROR_BUSY;
1422 else if (errno == ENODEV)
1423 return LIBUSB_ERROR_NO_DEVICE;
1425 usbi_err(HANDLE_CTX(handle),
1426 "claim interface failed, error %d errno %d", r, errno);
1427 return LIBUSB_ERROR_OTHER;
1432 static int release_interface(struct libusb_device_handle *handle, int iface)
1434 int fd = _device_handle_priv(handle)->fd;
1435 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1437 if (errno == ENODEV)
1438 return LIBUSB_ERROR_NO_DEVICE;
1440 usbi_err(HANDLE_CTX(handle),
1441 "release interface failed, error %d errno %d", r, errno);
1442 return LIBUSB_ERROR_OTHER;
1447 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1450 int fd = _device_handle_priv(handle)->fd;
1451 struct usbfs_setinterface setintf;
1454 setintf.interface = iface;
1455 setintf.altsetting = altsetting;
1456 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1458 if (errno == EINVAL)
1459 return LIBUSB_ERROR_NOT_FOUND;
1460 else if (errno == ENODEV)
1461 return LIBUSB_ERROR_NO_DEVICE;
1463 usbi_err(HANDLE_CTX(handle),
1464 "setintf failed error %d errno %d", r, errno);
1465 return LIBUSB_ERROR_OTHER;
1471 static int op_clear_halt(struct libusb_device_handle *handle,
1472 unsigned char endpoint)
1474 int fd = _device_handle_priv(handle)->fd;
1475 unsigned int _endpoint = endpoint;
1476 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1478 if (errno == ENOENT)
1479 return LIBUSB_ERROR_NOT_FOUND;
1480 else if (errno == ENODEV)
1481 return LIBUSB_ERROR_NO_DEVICE;
1483 usbi_err(HANDLE_CTX(handle),
1484 "clear_halt failed error %d errno %d", r, errno);
1485 return LIBUSB_ERROR_OTHER;
1491 static int op_reset_device(struct libusb_device_handle *handle)
1493 int fd = _device_handle_priv(handle)->fd;
1496 /* Doing a device reset will cause the usbfs driver to get unbound
1497 from any interfaces it is bound to. By voluntarily unbinding
1498 the usbfs driver ourself, we stop the kernel from rebinding
1499 the interface after reset (which would end up with the interface
1500 getting bound to the in kernel driver if any). */
1501 for (i = 0; i < USB_MAXINTERFACES; i++) {
1502 if (handle->claimed_interfaces & (1L << i)) {
1503 release_interface(handle, i);
1507 usbi_mutex_lock(&handle->lock);
1508 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1510 if (errno == ENODEV) {
1511 ret = LIBUSB_ERROR_NOT_FOUND;
1515 usbi_err(HANDLE_CTX(handle),
1516 "reset failed error %d errno %d", r, errno);
1517 ret = LIBUSB_ERROR_OTHER;
1521 /* And re-claim any interfaces which were claimed before the reset */
1522 for (i = 0; i < USB_MAXINTERFACES; i++) {
1523 if (handle->claimed_interfaces & (1L << i)) {
1525 * A driver may have completed modprobing during
1526 * IOCTL_USBFS_RESET, and bound itself as soon as
1527 * IOCTL_USBFS_RESET released the device lock
1529 r = detach_kernel_driver_and_claim(handle, i);
1531 usbi_warn(HANDLE_CTX(handle),
1532 "failed to re-claim interface %d after reset: %s",
1533 i, libusb_error_name(r));
1534 handle->claimed_interfaces &= ~(1L << i);
1535 ret = LIBUSB_ERROR_NOT_FOUND;
1540 usbi_mutex_unlock(&handle->lock);
1544 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1545 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1547 int r, fd = _device_handle_priv(handle)->fd;
1548 struct usbfs_streams *streams;
1550 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1551 return LIBUSB_ERROR_INVALID_PARAM;
1553 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1555 return LIBUSB_ERROR_NO_MEM;
1557 streams->num_streams = num_streams;
1558 streams->num_eps = num_endpoints;
1559 memcpy(streams->eps, endpoints, num_endpoints);
1561 r = ioctl(fd, req, streams);
1566 if (errno == ENOTTY)
1567 return LIBUSB_ERROR_NOT_SUPPORTED;
1568 else if (errno == EINVAL)
1569 return LIBUSB_ERROR_INVALID_PARAM;
1570 else if (errno == ENODEV)
1571 return LIBUSB_ERROR_NO_DEVICE;
1573 usbi_err(HANDLE_CTX(handle),
1574 "streams-ioctl failed error %d errno %d", r, errno);
1575 return LIBUSB_ERROR_OTHER;
1580 static int op_alloc_streams(struct libusb_device_handle *handle,
1581 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1583 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1584 num_streams, endpoints, num_endpoints);
1587 static int op_free_streams(struct libusb_device_handle *handle,
1588 unsigned char *endpoints, int num_endpoints)
1590 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1591 endpoints, num_endpoints);
1594 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1597 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1598 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1599 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1600 if (buffer == MAP_FAILED) {
1601 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1608 static int op_dev_mem_free(struct libusb_device_handle *handle,
1609 unsigned char *buffer, size_t len)
1611 if (munmap(buffer, len) != 0) {
1612 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1614 return LIBUSB_ERROR_OTHER;
1616 return LIBUSB_SUCCESS;
1620 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1623 int fd = _device_handle_priv(handle)->fd;
1624 struct usbfs_getdriver getdrv;
1627 getdrv.interface = interface;
1628 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1630 if (errno == ENODATA)
1632 else if (errno == ENODEV)
1633 return LIBUSB_ERROR_NO_DEVICE;
1635 usbi_err(HANDLE_CTX(handle),
1636 "get driver failed error %d errno %d", r, errno);
1637 return LIBUSB_ERROR_OTHER;
1640 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1643 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1646 int fd = _device_handle_priv(handle)->fd;
1647 struct usbfs_ioctl command;
1648 struct usbfs_getdriver getdrv;
1651 command.ifno = interface;
1652 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1653 command.data = NULL;
1655 getdrv.interface = interface;
1656 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1657 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1658 return LIBUSB_ERROR_NOT_FOUND;
1660 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1662 if (errno == ENODATA)
1663 return LIBUSB_ERROR_NOT_FOUND;
1664 else if (errno == EINVAL)
1665 return LIBUSB_ERROR_INVALID_PARAM;
1666 else if (errno == ENODEV)
1667 return LIBUSB_ERROR_NO_DEVICE;
1669 usbi_err(HANDLE_CTX(handle),
1670 "detach failed error %d errno %d", r, errno);
1671 return LIBUSB_ERROR_OTHER;
1677 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1680 int fd = _device_handle_priv(handle)->fd;
1681 struct usbfs_ioctl command;
1684 command.ifno = interface;
1685 command.ioctl_code = IOCTL_USBFS_CONNECT;
1686 command.data = NULL;
1688 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1690 if (errno == ENODATA)
1691 return LIBUSB_ERROR_NOT_FOUND;
1692 else if (errno == EINVAL)
1693 return LIBUSB_ERROR_INVALID_PARAM;
1694 else if (errno == ENODEV)
1695 return LIBUSB_ERROR_NO_DEVICE;
1696 else if (errno == EBUSY)
1697 return LIBUSB_ERROR_BUSY;
1699 usbi_err(HANDLE_CTX(handle),
1700 "attach failed error %d errno %d", r, errno);
1701 return LIBUSB_ERROR_OTHER;
1702 } else if (r == 0) {
1703 return LIBUSB_ERROR_NOT_FOUND;
1709 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1712 struct usbfs_disconnect_claim dc;
1713 int r, fd = _device_handle_priv(handle)->fd;
1715 dc.interface = interface;
1716 strcpy(dc.driver, "usbfs");
1717 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1718 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1719 if (r != 0 && errno != ENOTTY) {
1722 return LIBUSB_ERROR_BUSY;
1724 return LIBUSB_ERROR_INVALID_PARAM;
1726 return LIBUSB_ERROR_NO_DEVICE;
1728 usbi_err(HANDLE_CTX(handle),
1729 "disconnect-and-claim failed errno %d", errno);
1730 return LIBUSB_ERROR_OTHER;
1734 /* Fallback code for kernels which don't support the
1735 disconnect-and-claim ioctl */
1736 r = op_detach_kernel_driver(handle, interface);
1737 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1740 return claim_interface(handle, interface);
1743 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1745 if (handle->auto_detach_kernel_driver)
1746 return detach_kernel_driver_and_claim(handle, iface);
1748 return claim_interface(handle, iface);
1751 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1755 r = release_interface(handle, iface);
1759 if (handle->auto_detach_kernel_driver)
1760 op_attach_kernel_driver(handle, iface);
1765 static void op_destroy_device(struct libusb_device *dev)
1767 struct linux_device_priv *priv = _device_priv(dev);
1768 if (priv->descriptors)
1769 free(priv->descriptors);
1770 if (priv->sysfs_dir)
1771 free(priv->sysfs_dir);
1774 /* URBs are discarded in reverse order of submission to avoid races. */
1775 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1777 struct libusb_transfer *transfer =
1778 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1779 struct linux_transfer_priv *tpriv =
1780 usbi_transfer_get_os_priv(itransfer);
1781 struct linux_device_handle_priv *dpriv =
1782 _device_handle_priv(transfer->dev_handle);
1784 struct usbfs_urb *urb;
1786 for (i = last_plus_one - 1; i >= first; i--) {
1787 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1788 urb = tpriv->iso_urbs[i];
1790 urb = &tpriv->urbs[i];
1792 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1795 if (EINVAL == errno) {
1796 usbi_dbg("URB not found --> assuming ready to be reaped");
1797 if (i == (last_plus_one - 1))
1798 ret = LIBUSB_ERROR_NOT_FOUND;
1799 } else if (ENODEV == errno) {
1800 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1801 ret = LIBUSB_ERROR_NO_DEVICE;
1803 usbi_warn(TRANSFER_CTX(transfer),
1804 "unrecognised discard errno %d", errno);
1805 ret = LIBUSB_ERROR_OTHER;
1811 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1814 for (i = 0; i < tpriv->num_urbs; i++) {
1815 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1821 free(tpriv->iso_urbs);
1822 tpriv->iso_urbs = NULL;
1825 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1827 struct libusb_transfer *transfer =
1828 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1829 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1830 struct linux_device_handle_priv *dpriv =
1831 _device_handle_priv(transfer->dev_handle);
1832 struct usbfs_urb *urbs;
1833 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1834 == LIBUSB_ENDPOINT_OUT;
1835 int bulk_buffer_len, use_bulk_continuation;
1839 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1840 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1841 return LIBUSB_ERROR_NOT_SUPPORTED;
1844 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1845 * around this by splitting large transfers into 16k blocks, and then
1846 * submit all urbs at once. it would be simpler to submit one urb at
1847 * a time, but there is a big performance gain doing it this way.
1849 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1850 * using arbritary large transfers can still be a bad idea though, as
1851 * the kernel needs to allocate physical contiguous memory for this,
1852 * which may fail for large buffers.
1854 * The kernel solves this problem by splitting the transfer into
1855 * blocks itself when the host-controller is scatter-gather capable
1856 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1858 * Last, there is the issue of short-transfers when splitting, for
1859 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1860 * is needed, but this is not always available.
1862 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1863 /* Good! Just submit everything in one go */
1864 bulk_buffer_len = transfer->length ? transfer->length : 1;
1865 use_bulk_continuation = 0;
1866 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1867 /* Split the transfers and use bulk-continuation to
1868 avoid issues with short-transfers */
1869 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1870 use_bulk_continuation = 1;
1871 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1872 /* Don't split, assume the kernel can alloc the buffer
1873 (otherwise the submit will fail with -ENOMEM) */
1874 bulk_buffer_len = transfer->length ? transfer->length : 1;
1875 use_bulk_continuation = 0;
1877 /* Bad, splitting without bulk-continuation, short transfers
1878 which end before the last urb will not work reliable! */
1879 /* Note we don't warn here as this is "normal" on kernels <
1880 2.6.32 and not a problem for most applications */
1881 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1882 use_bulk_continuation = 0;
1885 int num_urbs = transfer->length / bulk_buffer_len;
1886 int last_urb_partial = 0;
1888 if (transfer->length == 0) {
1890 } else if ((transfer->length % bulk_buffer_len) > 0) {
1891 last_urb_partial = 1;
1894 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1896 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1898 return LIBUSB_ERROR_NO_MEM;
1900 tpriv->num_urbs = num_urbs;
1901 tpriv->num_retired = 0;
1902 tpriv->reap_action = NORMAL;
1903 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1905 for (i = 0; i < num_urbs; i++) {
1906 struct usbfs_urb *urb = &urbs[i];
1907 urb->usercontext = itransfer;
1908 switch (transfer->type) {
1909 case LIBUSB_TRANSFER_TYPE_BULK:
1910 urb->type = USBFS_URB_TYPE_BULK;
1913 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1914 urb->type = USBFS_URB_TYPE_BULK;
1915 urb->stream_id = itransfer->stream_id;
1917 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1918 urb->type = USBFS_URB_TYPE_INTERRUPT;
1921 urb->endpoint = transfer->endpoint;
1922 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1923 /* don't set the short not ok flag for the last URB */
1924 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1925 urb->flags = USBFS_URB_SHORT_NOT_OK;
1926 if (i == num_urbs - 1 && last_urb_partial)
1927 urb->buffer_length = transfer->length % bulk_buffer_len;
1928 else if (transfer->length == 0)
1929 urb->buffer_length = 0;
1931 urb->buffer_length = bulk_buffer_len;
1933 if (i > 0 && use_bulk_continuation)
1934 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1936 /* we have already checked that the flag is supported */
1937 if (is_out && i == num_urbs - 1 &&
1938 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1939 urb->flags |= USBFS_URB_ZERO_PACKET;
1941 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1943 if (errno == ENODEV) {
1944 r = LIBUSB_ERROR_NO_DEVICE;
1946 usbi_err(TRANSFER_CTX(transfer),
1947 "submiturb failed error %d errno=%d", r, errno);
1948 r = LIBUSB_ERROR_IO;
1951 /* if the first URB submission fails, we can simply free up and
1952 * return failure immediately. */
1954 usbi_dbg("first URB failed, easy peasy");
1960 /* if it's not the first URB that failed, the situation is a bit
1961 * tricky. we may need to discard all previous URBs. there are
1963 * - discarding is asynchronous - discarded urbs will be reaped
1964 * later. the user must not have freed the transfer when the
1965 * discarded URBs are reaped, otherwise libusb will be using
1967 * - the earlier URBs may have completed successfully and we do
1968 * not want to throw away any data.
1969 * - this URB failing may be no error; EREMOTEIO means that
1970 * this transfer simply didn't need all the URBs we submitted
1971 * so, we report that the transfer was submitted successfully and
1972 * in case of error we discard all previous URBs. later when
1973 * the final reap completes we can report error to the user,
1974 * or success if an earlier URB was completed successfully.
1976 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1978 /* The URBs we haven't submitted yet we count as already
1980 tpriv->num_retired += num_urbs - i;
1982 /* If we completed short then don't try to discard. */
1983 if (COMPLETED_EARLY == tpriv->reap_action)
1986 discard_urbs(itransfer, 0, i);
1988 usbi_dbg("reporting successful submission but waiting for %d "
1989 "discards before reporting error", i);
1997 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1999 struct libusb_transfer *transfer =
2000 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2001 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2002 struct linux_device_handle_priv *dpriv =
2003 _device_handle_priv(transfer->dev_handle);
2004 struct usbfs_urb **urbs;
2006 int num_packets = transfer->num_iso_packets;
2008 int this_urb_len = 0;
2010 int packet_offset = 0;
2011 unsigned int packet_len;
2012 unsigned char *urb_buffer = transfer->buffer;
2014 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2015 * at least three times, and it's difficult to accurately detect which
2016 * limit this running kernel might impose. so we attempt to submit
2017 * whatever the user has provided. if the kernel rejects the request
2018 * due to its size, we return an error indicating such to the user.
2021 /* calculate how many URBs we need */
2022 for (i = 0; i < num_packets; i++) {
2023 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
2024 packet_len = transfer->iso_packet_desc[i].length;
2026 if (packet_len > space_remaining) {
2028 this_urb_len = packet_len;
2029 /* check that we can actually support this packet length */
2030 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2031 return LIBUSB_ERROR_INVALID_PARAM;
2033 this_urb_len += packet_len;
2036 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2038 urbs = calloc(num_urbs, sizeof(*urbs));
2040 return LIBUSB_ERROR_NO_MEM;
2042 tpriv->iso_urbs = urbs;
2043 tpriv->num_urbs = num_urbs;
2044 tpriv->num_retired = 0;
2045 tpriv->reap_action = NORMAL;
2046 tpriv->iso_packet_offset = 0;
2048 /* allocate + initialize each URB with the correct number of packets */
2049 for (i = 0; i < num_urbs; i++) {
2050 struct usbfs_urb *urb;
2051 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2052 int urb_packet_offset = 0;
2053 unsigned char *urb_buffer_orig = urb_buffer;
2057 /* swallow up all the packets we can fit into this URB */
2058 while (packet_offset < transfer->num_iso_packets) {
2059 packet_len = transfer->iso_packet_desc[packet_offset].length;
2060 if (packet_len <= space_remaining_in_urb) {
2062 urb_packet_offset++;
2064 space_remaining_in_urb -= packet_len;
2065 urb_buffer += packet_len;
2067 /* it can't fit, save it for the next URB */
2072 alloc_size = sizeof(*urb)
2073 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2074 urb = calloc(1, alloc_size);
2076 free_iso_urbs(tpriv);
2077 return LIBUSB_ERROR_NO_MEM;
2081 /* populate packet lengths */
2082 for (j = 0, k = packet_offset - urb_packet_offset;
2083 k < packet_offset; k++, j++) {
2084 packet_len = transfer->iso_packet_desc[k].length;
2085 urb->buffer_length += packet_len;
2086 urb->iso_frame_desc[j].length = packet_len;
2089 urb->usercontext = itransfer;
2090 urb->type = USBFS_URB_TYPE_ISO;
2091 /* FIXME: interface for non-ASAP data? */
2092 urb->flags = USBFS_URB_ISO_ASAP;
2093 urb->endpoint = transfer->endpoint;
2094 urb->number_of_packets = urb_packet_offset;
2095 urb->buffer = urb_buffer_orig;
2099 for (i = 0; i < num_urbs; i++) {
2100 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2102 if (errno == ENODEV) {
2103 r = LIBUSB_ERROR_NO_DEVICE;
2104 } else if (errno == EINVAL) {
2105 usbi_warn(TRANSFER_CTX(transfer),
2106 "submiturb failed, transfer too large");
2107 r = LIBUSB_ERROR_INVALID_PARAM;
2109 usbi_err(TRANSFER_CTX(transfer),
2110 "submiturb failed error %d errno=%d", r, errno);
2111 r = LIBUSB_ERROR_IO;
2114 /* if the first URB submission fails, we can simply free up and
2115 * return failure immediately. */
2117 usbi_dbg("first URB failed, easy peasy");
2118 free_iso_urbs(tpriv);
2122 /* if it's not the first URB that failed, the situation is a bit
2123 * tricky. we must discard all previous URBs. there are
2125 * - discarding is asynchronous - discarded urbs will be reaped
2126 * later. the user must not have freed the transfer when the
2127 * discarded URBs are reaped, otherwise libusb will be using
2129 * - the earlier URBs may have completed successfully and we do
2130 * not want to throw away any data.
2131 * so, in this case we discard all the previous URBs BUT we report
2132 * that the transfer was submitted successfully. then later when
2133 * the final discard completes we can report error to the user.
2135 tpriv->reap_action = SUBMIT_FAILED;
2137 /* The URBs we haven't submitted yet we count as already
2139 tpriv->num_retired = num_urbs - i;
2140 discard_urbs(itransfer, 0, i);
2142 usbi_dbg("reporting successful submission but waiting for %d "
2143 "discards before reporting error", i);
2151 static int submit_control_transfer(struct usbi_transfer *itransfer)
2153 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2154 struct libusb_transfer *transfer =
2155 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2156 struct linux_device_handle_priv *dpriv =
2157 _device_handle_priv(transfer->dev_handle);
2158 struct usbfs_urb *urb;
2161 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2162 return LIBUSB_ERROR_INVALID_PARAM;
2164 urb = calloc(1, sizeof(struct usbfs_urb));
2166 return LIBUSB_ERROR_NO_MEM;
2168 tpriv->num_urbs = 1;
2169 tpriv->reap_action = NORMAL;
2171 urb->usercontext = itransfer;
2172 urb->type = USBFS_URB_TYPE_CONTROL;
2173 urb->endpoint = transfer->endpoint;
2174 urb->buffer = transfer->buffer;
2175 urb->buffer_length = transfer->length;
2177 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2181 if (errno == ENODEV)
2182 return LIBUSB_ERROR_NO_DEVICE;
2184 usbi_err(TRANSFER_CTX(transfer),
2185 "submiturb failed error %d errno=%d", r, errno);
2186 return LIBUSB_ERROR_IO;
2191 static int op_submit_transfer(struct usbi_transfer *itransfer)
2193 struct libusb_transfer *transfer =
2194 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2196 switch (transfer->type) {
2197 case LIBUSB_TRANSFER_TYPE_CONTROL:
2198 return submit_control_transfer(itransfer);
2199 case LIBUSB_TRANSFER_TYPE_BULK:
2200 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2201 return submit_bulk_transfer(itransfer);
2202 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2203 return submit_bulk_transfer(itransfer);
2204 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2205 return submit_iso_transfer(itransfer);
2207 usbi_err(TRANSFER_CTX(transfer),
2208 "unknown endpoint type %d", transfer->type);
2209 return LIBUSB_ERROR_INVALID_PARAM;
2213 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2215 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2216 struct libusb_transfer *transfer =
2217 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2221 return LIBUSB_ERROR_NOT_FOUND;
2223 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2227 switch (transfer->type) {
2228 case LIBUSB_TRANSFER_TYPE_BULK:
2229 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2230 if (tpriv->reap_action == ERROR)
2232 /* else, fall through */
2234 tpriv->reap_action = CANCELLED;
2240 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2242 struct libusb_transfer *transfer =
2243 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2244 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2246 /* urbs can be freed also in submit_transfer so lock mutex first */
2247 switch (transfer->type) {
2248 case LIBUSB_TRANSFER_TYPE_CONTROL:
2249 case LIBUSB_TRANSFER_TYPE_BULK:
2250 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2251 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2257 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2258 if (tpriv->iso_urbs) {
2259 free_iso_urbs(tpriv);
2260 tpriv->iso_urbs = NULL;
2264 usbi_err(TRANSFER_CTX(transfer),
2265 "unknown endpoint type %d", transfer->type);
2269 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2270 struct usbfs_urb *urb)
2272 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2273 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2274 int urb_idx = urb - tpriv->urbs;
2276 usbi_mutex_lock(&itransfer->lock);
2277 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2278 urb_idx + 1, tpriv->num_urbs);
2280 tpriv->num_retired++;
2282 if (tpriv->reap_action != NORMAL) {
2283 /* cancelled, submit_fail, or completed early */
2284 usbi_dbg("abnormal reap: urb status %d", urb->status);
2286 /* even though we're in the process of cancelling, it's possible that
2287 * we may receive some data in these URBs that we don't want to lose.
2289 * 1. while the kernel is cancelling all the packets that make up an
2290 * URB, a few of them might complete. so we get back a successful
2291 * cancellation *and* some data.
2292 * 2. we receive a short URB which marks the early completion condition,
2293 * so we start cancelling the remaining URBs. however, we're too
2294 * slow and another URB completes (or at least completes partially).
2295 * (this can't happen since we always use BULK_CONTINUATION.)
2297 * When this happens, our objectives are not to lose any "surplus" data,
2298 * and also to stick it at the end of the previously-received data
2299 * (closing any holes), so that libusb reports the total amount of
2300 * transferred data and presents it in a contiguous chunk.
2302 if (urb->actual_length > 0) {
2303 unsigned char *target = transfer->buffer + itransfer->transferred;
2304 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2305 if (urb->buffer != target) {
2306 usbi_dbg("moving surplus data from offset %d to offset %d",
2307 (unsigned char *) urb->buffer - transfer->buffer,
2308 target - transfer->buffer);
2309 memmove(target, urb->buffer, urb->actual_length);
2311 itransfer->transferred += urb->actual_length;
2314 if (tpriv->num_retired == tpriv->num_urbs) {
2315 usbi_dbg("abnormal reap: last URB handled, reporting");
2316 if (tpriv->reap_action != COMPLETED_EARLY &&
2317 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2318 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2324 itransfer->transferred += urb->actual_length;
2326 /* Many of these errors can occur on *any* urb of a multi-urb
2327 * transfer. When they do, we tear down the rest of the transfer.
2329 switch (urb->status) {
2332 case -EREMOTEIO: /* short transfer */
2334 case -ENOENT: /* cancelled */
2339 usbi_dbg("device removed");
2340 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2341 goto cancel_remaining;
2343 usbi_dbg("detected endpoint stall");
2344 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2345 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2346 goto cancel_remaining;
2348 /* overflow can only ever occur in the last urb */
2349 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2350 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2351 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2358 usbi_dbg("low level error %d", urb->status);
2359 tpriv->reap_action = ERROR;
2360 goto cancel_remaining;
2362 usbi_warn(ITRANSFER_CTX(itransfer),
2363 "unrecognised urb status %d", urb->status);
2364 tpriv->reap_action = ERROR;
2365 goto cancel_remaining;
2368 /* if we're the last urb or we got less data than requested then we're
2370 if (urb_idx == tpriv->num_urbs - 1) {
2371 usbi_dbg("last URB in transfer --> complete!");
2373 } else if (urb->actual_length < urb->buffer_length) {
2374 usbi_dbg("short transfer %d/%d --> complete!",
2375 urb->actual_length, urb->buffer_length);
2376 if (tpriv->reap_action == NORMAL)
2377 tpriv->reap_action = COMPLETED_EARLY;
2382 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2383 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2385 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2388 /* cancel remaining urbs and wait for their completion before
2389 * reporting results */
2390 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2393 usbi_mutex_unlock(&itransfer->lock);
2399 usbi_mutex_unlock(&itransfer->lock);
2400 return CANCELLED == tpriv->reap_action ?
2401 usbi_handle_transfer_cancellation(itransfer) :
2402 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2405 static int handle_iso_completion(struct usbi_transfer *itransfer,
2406 struct usbfs_urb *urb)
2408 struct libusb_transfer *transfer =
2409 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2410 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2411 int num_urbs = tpriv->num_urbs;
2414 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2416 usbi_mutex_lock(&itransfer->lock);
2417 for (i = 0; i < num_urbs; i++) {
2418 if (urb == tpriv->iso_urbs[i]) {
2424 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2425 usbi_mutex_unlock(&itransfer->lock);
2426 return LIBUSB_ERROR_NOT_FOUND;
2429 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2432 /* copy isochronous results back in */
2434 for (i = 0; i < urb->number_of_packets; i++) {
2435 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2436 struct libusb_iso_packet_descriptor *lib_desc =
2437 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2438 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2439 switch (urb_desc->status) {
2442 case -ENOENT: /* cancelled */
2447 usbi_dbg("device removed");
2448 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2451 usbi_dbg("detected endpoint stall");
2452 lib_desc->status = LIBUSB_TRANSFER_STALL;
2455 usbi_dbg("overflow error");
2456 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2464 usbi_dbg("low-level USB error %d", urb_desc->status);
2465 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2468 usbi_warn(TRANSFER_CTX(transfer),
2469 "unrecognised urb status %d", urb_desc->status);
2470 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2473 lib_desc->actual_length = urb_desc->actual_length;
2476 tpriv->num_retired++;
2478 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2479 usbi_dbg("CANCEL: urb status %d", urb->status);
2481 if (tpriv->num_retired == num_urbs) {
2482 usbi_dbg("CANCEL: last URB handled, reporting");
2483 free_iso_urbs(tpriv);
2484 if (tpriv->reap_action == CANCELLED) {
2485 usbi_mutex_unlock(&itransfer->lock);
2486 return usbi_handle_transfer_cancellation(itransfer);
2488 usbi_mutex_unlock(&itransfer->lock);
2489 return usbi_handle_transfer_completion(itransfer,
2490 LIBUSB_TRANSFER_ERROR);
2496 switch (urb->status) {
2499 case -ENOENT: /* cancelled */
2503 usbi_dbg("device removed");
2504 status = LIBUSB_TRANSFER_NO_DEVICE;
2507 usbi_warn(TRANSFER_CTX(transfer),
2508 "unrecognised urb status %d", urb->status);
2509 status = LIBUSB_TRANSFER_ERROR;
2513 /* if we're the last urb then we're done */
2514 if (urb_idx == num_urbs) {
2515 usbi_dbg("last URB in transfer --> complete!");
2516 free_iso_urbs(tpriv);
2517 usbi_mutex_unlock(&itransfer->lock);
2518 return usbi_handle_transfer_completion(itransfer, status);
2522 usbi_mutex_unlock(&itransfer->lock);
2526 static int handle_control_completion(struct usbi_transfer *itransfer,
2527 struct usbfs_urb *urb)
2529 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2532 usbi_mutex_lock(&itransfer->lock);
2533 usbi_dbg("handling completion status %d", urb->status);
2535 itransfer->transferred += urb->actual_length;
2537 if (tpriv->reap_action == CANCELLED) {
2538 if (urb->status != 0 && urb->status != -ENOENT)
2539 usbi_warn(ITRANSFER_CTX(itransfer),
2540 "cancel: unrecognised urb status %d", urb->status);
2543 usbi_mutex_unlock(&itransfer->lock);
2544 return usbi_handle_transfer_cancellation(itransfer);
2547 switch (urb->status) {
2549 status = LIBUSB_TRANSFER_COMPLETED;
2551 case -ENOENT: /* cancelled */
2552 status = LIBUSB_TRANSFER_CANCELLED;
2556 usbi_dbg("device removed");
2557 status = LIBUSB_TRANSFER_NO_DEVICE;
2560 usbi_dbg("unsupported control request");
2561 status = LIBUSB_TRANSFER_STALL;
2564 usbi_dbg("control overflow error");
2565 status = LIBUSB_TRANSFER_OVERFLOW;
2572 usbi_dbg("low-level bus error occurred");
2573 status = LIBUSB_TRANSFER_ERROR;
2576 usbi_warn(ITRANSFER_CTX(itransfer),
2577 "unrecognised urb status %d", urb->status);
2578 status = LIBUSB_TRANSFER_ERROR;
2584 usbi_mutex_unlock(&itransfer->lock);
2585 return usbi_handle_transfer_completion(itransfer, status);
2588 static int reap_for_handle(struct libusb_device_handle *handle)
2590 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2592 struct usbfs_urb *urb;
2593 struct usbi_transfer *itransfer;
2594 struct libusb_transfer *transfer;
2596 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2597 if (r == -1 && errno == EAGAIN)
2600 if (errno == ENODEV)
2601 return LIBUSB_ERROR_NO_DEVICE;
2603 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2605 return LIBUSB_ERROR_IO;
2608 itransfer = urb->usercontext;
2609 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2611 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2612 urb->actual_length);
2614 switch (transfer->type) {
2615 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2616 return handle_iso_completion(itransfer, urb);
2617 case LIBUSB_TRANSFER_TYPE_BULK:
2618 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2619 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2620 return handle_bulk_completion(itransfer, urb);
2621 case LIBUSB_TRANSFER_TYPE_CONTROL:
2622 return handle_control_completion(itransfer, urb);
2624 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2626 return LIBUSB_ERROR_OTHER;
2630 static int op_handle_events(struct libusb_context *ctx,
2631 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2636 usbi_mutex_lock(&ctx->open_devs_lock);
2637 for (i = 0; i < nfds && num_ready > 0; i++) {
2638 struct pollfd *pollfd = &fds[i];
2639 struct libusb_device_handle *handle;
2640 struct linux_device_handle_priv *hpriv = NULL;
2642 if (!pollfd->revents)
2646 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2647 hpriv = _device_handle_priv(handle);
2648 if (hpriv->fd == pollfd->fd)
2652 if (!hpriv || hpriv->fd != pollfd->fd) {
2653 usbi_err(ctx, "cannot find handle for fd %d",
2658 if (pollfd->revents & POLLERR) {
2659 /* remove the fd from the pollfd set so that it doesn't continuously
2660 * trigger an event, and flag that it has been removed so op_close()
2661 * doesn't try to remove it a second time */
2662 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2663 hpriv->fd_removed = 1;
2665 /* device will still be marked as attached if hotplug monitor thread
2666 * hasn't processed remove event yet */
2667 usbi_mutex_static_lock(&linux_hotplug_lock);
2668 if (handle->dev->attached)
2669 linux_device_disconnected(handle->dev->bus_number,
2670 handle->dev->device_address);
2671 usbi_mutex_static_unlock(&linux_hotplug_lock);
2673 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2675 r = reap_for_handle(handle);
2679 usbi_handle_disconnect(handle);
2684 r = reap_for_handle(handle);
2686 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2694 usbi_mutex_unlock(&ctx->open_devs_lock);
2698 static int op_clock_gettime(int clk_id, struct timespec *tp)
2701 case USBI_CLOCK_MONOTONIC:
2702 return clock_gettime(monotonic_clkid, tp);
2703 case USBI_CLOCK_REALTIME:
2704 return clock_gettime(CLOCK_REALTIME, tp);
2706 return LIBUSB_ERROR_INVALID_PARAM;
2710 #ifdef USBI_TIMERFD_AVAILABLE
2711 static clockid_t op_get_timerfd_clockid(void)
2713 return monotonic_clkid;
2718 const struct usbi_os_backend usbi_backend = {
2719 .name = "Linux usbfs",
2720 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2723 .get_device_list = NULL,
2724 .hotplug_poll = op_hotplug_poll,
2725 .get_device_descriptor = op_get_device_descriptor,
2726 .get_active_config_descriptor = op_get_active_config_descriptor,
2727 .get_config_descriptor = op_get_config_descriptor,
2728 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2732 .get_configuration = op_get_configuration,
2733 .set_configuration = op_set_configuration,
2734 .claim_interface = op_claim_interface,
2735 .release_interface = op_release_interface,
2737 .set_interface_altsetting = op_set_interface,
2738 .clear_halt = op_clear_halt,
2739 .reset_device = op_reset_device,
2741 .alloc_streams = op_alloc_streams,
2742 .free_streams = op_free_streams,
2744 .dev_mem_alloc = op_dev_mem_alloc,
2745 .dev_mem_free = op_dev_mem_free,
2747 .kernel_driver_active = op_kernel_driver_active,
2748 .detach_kernel_driver = op_detach_kernel_driver,
2749 .attach_kernel_driver = op_attach_kernel_driver,
2751 .destroy_device = op_destroy_device,
2753 .submit_transfer = op_submit_transfer,
2754 .cancel_transfer = op_cancel_transfer,
2755 .clear_transfer_priv = op_clear_transfer_priv,
2757 .handle_events = op_handle_events,
2759 .clock_gettime = op_clock_gettime,
2761 #ifdef USBI_TIMERFD_AVAILABLE
2762 .get_timerfd_clockid = op_get_timerfd_clockid,
2765 .device_priv_size = sizeof(struct linux_device_priv),
2766 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2767 .transfer_priv_size = sizeof(struct linux_transfer_priv),