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 has changed the maximum length of an individual isochronous packet
85 * over time. Initially this limit was 1,023 bytes, but Linux 2.6.18
86 * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
87 * 8,192 bytes to support higher bandwidth devices. Linux 3.10
88 * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
89 * value to 49,152 bytes to support super speed devices.
91 static unsigned int max_iso_packet_len = 0;
93 /* Linux 2.6.23 adds support for O_CLOEXEC when opening files, which marks the
94 * close-on-exec flag in the underlying file descriptor. */
95 static int supports_flag_cloexec = -1;
97 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
98 * allows us to mark URBs as being part of a specific logical transfer when
99 * we submit them to the kernel. then, on any error except a cancellation, all
100 * URBs within that transfer will be cancelled and no more URBs will be
101 * accepted for the transfer, meaning that no more data can creep in.
103 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
104 * (in either direction) except the first.
105 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
106 * last; it means that the kernel should treat a short reply as an error.
107 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
108 * transfers can't be short unless there's already some sort of error), and
109 * setting this flag is disallowed (a kernel with USB debugging enabled will
112 static int supports_flag_bulk_continuation = -1;
114 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
115 * allows us to mark URBs that should be followed by a zero length data
116 * packet, which can be required by device- or class-specific protocols.
118 static int supports_flag_zero_packet = -1;
120 /* clock ID for monotonic clock, as not all clock sources are available on all
121 * systems. appropriate choice made at initialization time. */
122 static clockid_t monotonic_clkid = -1;
124 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
125 * to sysfs, so we can relate devices. This also implies that we can read
126 * the active configuration through bConfigurationValue */
127 static int sysfs_can_relate_devices = -1;
129 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
130 * config descriptors (rather then just the active config) to the sysfs
131 * descriptors file, so from then on we can use them. */
132 static int sysfs_has_descriptors = -1;
134 /* how many times have we initted (and not exited) ? */
135 static int init_count = 0;
137 /* Serialize hotplug start/stop */
138 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
139 /* Serialize scan-devices, event-thread, and poll */
140 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
142 static int linux_start_event_monitor(void);
143 static int linux_stop_event_monitor(void);
144 static int linux_scan_devices(struct libusb_context *ctx);
145 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
146 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
148 #if !defined(USE_UDEV)
149 static int linux_default_scan_devices (struct libusb_context *ctx);
152 struct kernel_version {
158 struct linux_device_priv {
160 unsigned char *descriptors;
162 int active_config; /* cache val for !sysfs_can_relate_devices */
165 struct linux_device_handle_priv {
174 /* submission failed after the first URB, so await cancellation/completion
175 * of all the others */
178 /* cancelled by user or timeout */
181 /* completed multi-URB transfer in non-final URB */
184 /* one or more urbs encountered a low-level error */
188 struct linux_transfer_priv {
190 struct usbfs_urb *urbs;
191 struct usbfs_urb **iso_urbs;
194 enum reap_action reap_action;
197 enum libusb_transfer_status reap_status;
199 /* next iso packet in user-supplied transfer to be populated */
200 int iso_packet_offset;
203 static int _open(const char *path, int flags)
205 #if defined(O_CLOEXEC)
206 if (supports_flag_cloexec)
207 return open(path, flags | O_CLOEXEC);
210 return open(path, flags);
213 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
215 struct libusb_context *ctx = DEVICE_CTX(dev);
221 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
222 usbfs_path, dev->bus_number, dev->device_address);
224 snprintf(path, PATH_MAX, "%s/%03d/%03d",
225 usbfs_path, dev->bus_number, dev->device_address);
227 fd = _open(path, mode);
229 return fd; /* Success */
231 if (errno == ENOENT) {
233 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
235 /* Wait 10ms for USB device path creation.*/
236 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
238 fd = _open(path, mode);
240 return fd; /* Success */
244 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
245 path, strerror(errno));
246 if (errno == EACCES && mode == O_RDWR)
247 usbi_err(ctx, "libusb requires write access to USB "
252 return LIBUSB_ERROR_ACCESS;
254 return LIBUSB_ERROR_NO_DEVICE;
255 return LIBUSB_ERROR_IO;
258 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
260 return (struct linux_device_priv *) dev->os_priv;
263 static struct linux_device_handle_priv *_device_handle_priv(
264 struct libusb_device_handle *handle)
266 return (struct linux_device_handle_priv *) handle->os_priv;
269 /* check dirent for a /dev/usbdev%d.%d name
270 * optionally return bus/device on success */
271 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
275 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
278 usbi_dbg("found: %s", entry->d_name);
286 static int check_usb_vfs(const char *dirname)
289 struct dirent *entry;
292 dir = opendir(dirname);
296 while ((entry = readdir(dir)) != NULL) {
297 if (entry->d_name[0] == '.')
300 /* We assume if we find any files that it must be the right place */
309 static const char *find_usbfs_path(void)
311 const char *path = "/dev/bus/usb";
312 const char *ret = NULL;
314 if (check_usb_vfs(path)) {
317 path = "/proc/bus/usb";
318 if (check_usb_vfs(path))
322 /* look for /dev/usbdev*.* if the normal places fail */
324 struct dirent *entry;
330 while ((entry = readdir(dir)) != NULL) {
331 if (_is_usbdev_entry(entry, NULL, NULL)) {
332 /* found one; that's enough */
342 /* On udev based systems without any usb-devices /dev/bus/usb will not
343 * exist. So if we've not found anything and we're using udev for hotplug
344 * simply assume /dev/bus/usb rather then making libusb_init fail.
345 * Make the same assumption for Android where SELinux policies might block us
346 * from reading /dev on newer devices. */
347 #if defined(USE_UDEV) || defined(__ANDROID__)
349 ret = "/dev/bus/usb";
353 usbi_dbg("found usbfs at %s", ret);
358 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
359 * seem to lack it). fall back to REALTIME if we have to. */
360 static clockid_t find_monotonic_clock(void)
362 #ifdef CLOCK_MONOTONIC
366 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
367 * because it's not available through timerfd */
368 r = clock_gettime(CLOCK_MONOTONIC, &ts);
370 return CLOCK_MONOTONIC;
371 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
374 return CLOCK_REALTIME;
377 static int get_kernel_version(struct libusb_context *ctx,
378 struct kernel_version *ver)
383 if (uname(&uts) < 0) {
384 usbi_err(ctx, "uname failed, errno %d", errno);
388 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
390 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
399 usbi_dbg("reported kernel version is %s", uts.release);
404 static int kernel_version_ge(const struct kernel_version *ver,
405 int major, int minor, int sublevel)
407 if (ver->major > major)
409 else if (ver->major < major)
412 /* kmajor == major */
413 if (ver->minor == -1 && ver->sublevel == -1)
414 return 0 == minor && 0 == sublevel;
415 else if (ver->minor > minor)
417 else if (ver->minor < minor)
420 /* kminor == minor */
421 if (ver->sublevel == -1)
422 return 0 == sublevel;
424 return ver->sublevel >= sublevel;
427 static int op_init(struct libusb_context *ctx)
429 struct kernel_version kversion;
433 usbfs_path = find_usbfs_path();
435 usbi_err(ctx, "could not find usbfs");
436 return LIBUSB_ERROR_OTHER;
439 if (monotonic_clkid == -1)
440 monotonic_clkid = find_monotonic_clock();
442 if (get_kernel_version(ctx, &kversion) < 0)
443 return LIBUSB_ERROR_OTHER;
445 if (supports_flag_cloexec == -1) {
446 /* O_CLOEXEC flag available from Linux 2.6.23 */
447 supports_flag_cloexec = kernel_version_ge(&kversion,2,6,23);
450 if (supports_flag_bulk_continuation == -1) {
451 /* bulk continuation URB flag available from Linux 2.6.32 */
452 supports_flag_bulk_continuation = kernel_version_ge(&kversion,2,6,32);
455 if (supports_flag_bulk_continuation)
456 usbi_dbg("bulk continuation flag supported");
458 if (-1 == supports_flag_zero_packet) {
459 /* zero length packet URB flag fixed since Linux 2.6.31 */
460 supports_flag_zero_packet = kernel_version_ge(&kversion,2,6,31);
463 if (supports_flag_zero_packet)
464 usbi_dbg("zero length packet flag supported");
466 if (!max_iso_packet_len) {
467 if (kernel_version_ge(&kversion,3,10,0))
468 max_iso_packet_len = 49152;
469 else if (kernel_version_ge(&kversion,2,6,18))
470 max_iso_packet_len = 8192;
472 max_iso_packet_len = 1023;
475 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
477 if (-1 == sysfs_has_descriptors) {
478 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
479 sysfs_has_descriptors = kernel_version_ge(&kversion,2,6,26);
482 if (-1 == sysfs_can_relate_devices) {
483 /* sysfs has busnum since Linux 2.6.22 */
484 sysfs_can_relate_devices = kernel_version_ge(&kversion,2,6,22);
487 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
488 r = stat(SYSFS_DEVICE_PATH, &statbuf);
489 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
490 usbi_warn(ctx, "sysfs not mounted");
491 sysfs_can_relate_devices = 0;
492 sysfs_has_descriptors = 0;
496 if (sysfs_can_relate_devices)
497 usbi_dbg("sysfs can relate devices");
499 if (sysfs_has_descriptors)
500 usbi_dbg("sysfs has complete descriptors");
502 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
504 if (init_count == 0) {
505 /* start up hotplug event handler */
506 r = linux_start_event_monitor();
508 if (r == LIBUSB_SUCCESS) {
509 r = linux_scan_devices(ctx);
510 if (r == LIBUSB_SUCCESS)
512 else if (init_count == 0)
513 linux_stop_event_monitor();
515 usbi_err(ctx, "error starting hotplug event monitor");
516 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
521 static void op_exit(struct libusb_context *ctx)
524 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
525 assert(init_count != 0);
527 /* tear down event handler */
528 (void)linux_stop_event_monitor();
530 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
533 static int linux_start_event_monitor(void)
535 #if defined(USE_UDEV)
536 return linux_udev_start_event_monitor();
538 return linux_netlink_start_event_monitor();
542 static int linux_stop_event_monitor(void)
544 #if defined(USE_UDEV)
545 return linux_udev_stop_event_monitor();
547 return linux_netlink_stop_event_monitor();
551 static int linux_scan_devices(struct libusb_context *ctx)
555 usbi_mutex_static_lock(&linux_hotplug_lock);
557 #if defined(USE_UDEV)
558 ret = linux_udev_scan_devices(ctx);
560 ret = linux_default_scan_devices(ctx);
563 usbi_mutex_static_unlock(&linux_hotplug_lock);
568 static void op_hotplug_poll(void)
570 #if defined(USE_UDEV)
571 linux_udev_hotplug_poll();
573 linux_netlink_hotplug_poll();
577 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
579 struct linux_device_priv *priv = _device_priv(dev);
580 char filename[PATH_MAX];
583 snprintf(filename, PATH_MAX, "%s/%s/%s",
584 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
585 fd = _open(filename, O_RDONLY);
587 usbi_err(DEVICE_CTX(dev),
588 "open %s failed ret=%d errno=%d", filename, fd, errno);
589 return LIBUSB_ERROR_IO;
595 /* Note only suitable for attributes which always read >= 0, < 0 is error */
596 static int __read_sysfs_attr(struct libusb_context *ctx,
597 const char *devname, const char *attr)
599 char filename[PATH_MAX];
603 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
605 fd = _open(filename, O_RDONLY);
607 if (errno == ENOENT) {
608 /* File doesn't exist. Assume the device has been
609 disconnected (see trac ticket #70). */
610 return LIBUSB_ERROR_NO_DEVICE;
612 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
613 return LIBUSB_ERROR_IO;
618 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
620 return LIBUSB_ERROR_OTHER;
623 r = fscanf(f, "%d", &value);
626 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
627 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
630 usbi_err(ctx, "%s contains a negative value", filename);
631 return LIBUSB_ERROR_IO;
637 static int op_get_device_descriptor(struct libusb_device *dev,
638 unsigned char *buffer, int *host_endian)
640 struct linux_device_priv *priv = _device_priv(dev);
642 *host_endian = (priv->sysfs_dir && sysfs_has_descriptors) ? 0 : 1;
643 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
648 /* read the bConfigurationValue for a device */
649 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
652 char tmp[5] = {0, 0, 0, 0, 0};
657 fd = _open_sysfs_attr(dev, "bConfigurationValue");
661 r = read(fd, tmp, sizeof(tmp));
664 usbi_err(DEVICE_CTX(dev),
665 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
666 return LIBUSB_ERROR_IO;
668 usbi_dbg("device unconfigured");
673 if (tmp[sizeof(tmp) - 1] != 0) {
674 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
675 return LIBUSB_ERROR_IO;
676 } else if (tmp[0] == 0) {
677 usbi_err(DEVICE_CTX(dev), "no configuration value?");
678 return LIBUSB_ERROR_IO;
681 num = strtol(tmp, &endptr, 10);
683 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
684 return LIBUSB_ERROR_IO;
691 int linux_get_device_address (struct libusb_context *ctx, int detached,
692 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
693 const char *sys_name, int fd)
695 char proc_path[PATH_MAX], fd_path[PATH_MAX];
699 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
700 /* can't use sysfs to read the bus and device number if the
701 * device has been detached */
702 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
703 if (NULL == dev_node && fd >= 0) {
704 /* try to retrieve the device node from fd */
705 snprintf(proc_path, PATH_MAX, "/proc/self/fd/%d", fd);
706 r = readlink(proc_path, fd_path, PATH_MAX);
710 if (NULL == dev_node) {
711 return LIBUSB_ERROR_OTHER;
714 /* will this work with all supported kernel versions? */
715 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
716 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
717 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
718 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
720 return LIBUSB_ERROR_OTHER;
723 return LIBUSB_SUCCESS;
726 usbi_dbg("scan %s", sys_name);
728 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
731 if (sysfs_attr > 255)
732 return LIBUSB_ERROR_INVALID_PARAM;
733 *busnum = (uint8_t) sysfs_attr;
735 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
738 if (sysfs_attr > 255)
739 return LIBUSB_ERROR_INVALID_PARAM;
741 *devaddr = (uint8_t) sysfs_attr;
743 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
745 return LIBUSB_SUCCESS;
748 /* Return offset of the next descriptor with the given type */
749 static int seek_to_next_descriptor(struct libusb_context *ctx,
750 uint8_t descriptor_type, unsigned char *buffer, int size)
752 struct usb_descriptor_header header;
755 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
757 return LIBUSB_ERROR_NOT_FOUND;
760 usbi_err(ctx, "short descriptor read %d/2", size);
761 return LIBUSB_ERROR_IO;
763 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
765 if (i && header.bDescriptorType == descriptor_type)
768 usbi_err(ctx, "bLength overflow by %d bytes", -size);
769 return LIBUSB_ERROR_IO;
772 /* Return offset to next config */
773 static int seek_to_next_config(struct libusb_device *dev,
774 unsigned char *buffer, int size)
776 struct libusb_context *ctx = DEVICE_CTX(dev);
777 struct linux_device_priv *priv = _device_priv(dev);
778 struct libusb_config_descriptor config;
781 return LIBUSB_ERROR_NOT_FOUND;
783 if (size < LIBUSB_DT_CONFIG_SIZE) {
784 usbi_err(ctx, "short descriptor read %d/%d",
785 size, LIBUSB_DT_CONFIG_SIZE);
786 return LIBUSB_ERROR_IO;
789 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
790 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
791 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
792 config.bDescriptorType);
793 return LIBUSB_ERROR_IO;
797 * In usbfs the config descriptors are config.wTotalLength bytes apart,
798 * with any short reads from the device appearing as holes in the file.
800 * In sysfs wTotalLength is ignored, instead the kernel returns a
801 * config descriptor with verified bLength fields, with descriptors
802 * with an invalid bLength removed.
804 if (priv->sysfs_dir && sysfs_has_descriptors) {
805 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
807 if (next == LIBUSB_ERROR_NOT_FOUND)
812 if (next != config.wTotalLength)
813 usbi_warn(ctx, "config length mismatch wTotalLength "
814 "%d real %d", config.wTotalLength, next);
817 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
818 usbi_err(ctx, "invalid wTotalLength %d",
819 config.wTotalLength);
820 return LIBUSB_ERROR_IO;
821 } else if (config.wTotalLength > size) {
822 usbi_warn(ctx, "short descriptor read %d/%d",
823 size, config.wTotalLength);
826 return config.wTotalLength;
830 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
831 uint8_t value, unsigned char **buffer, int *host_endian)
833 struct linux_device_priv *priv = _device_priv(dev);
834 unsigned char *descriptors = priv->descriptors;
835 int size = priv->descriptors_len;
836 struct libusb_config_descriptor *config;
839 /* Unlike the device desc. config descs. are always in raw format */
842 /* Skip device header */
843 descriptors += DEVICE_DESC_LENGTH;
844 size -= DEVICE_DESC_LENGTH;
846 /* Seek till the config is found, or till "EOF" */
848 int next = seek_to_next_config(dev, descriptors, size);
851 config = (struct libusb_config_descriptor *)descriptors;
852 if (config->bConfigurationValue == value) {
853 *buffer = descriptors;
861 static int op_get_active_config_descriptor(struct libusb_device *dev,
862 unsigned char *buffer, size_t len, int *host_endian)
864 struct linux_device_priv *priv = _device_priv(dev);
866 unsigned char *config_desc;
868 if (priv->sysfs_dir && sysfs_can_relate_devices) {
869 r = sysfs_get_active_config(dev, &config);
873 /* Use cached bConfigurationValue */
874 config = priv->active_config;
877 return LIBUSB_ERROR_NOT_FOUND;
879 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
884 len = MIN(len, (size_t)r);
885 memcpy(buffer, config_desc, len);
889 static int op_get_config_descriptor(struct libusb_device *dev,
890 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
892 struct linux_device_priv *priv = _device_priv(dev);
893 unsigned char *descriptors = priv->descriptors;
894 int i, r, size = priv->descriptors_len;
896 /* Unlike the device desc. config descs. are always in raw format */
899 /* Skip device header */
900 descriptors += DEVICE_DESC_LENGTH;
901 size -= DEVICE_DESC_LENGTH;
903 /* Seek till the config is found, or till "EOF" */
905 r = seek_to_next_config(dev, descriptors, size);
908 if (i == config_index)
914 len = MIN(len, (size_t)r);
915 memcpy(buffer, descriptors, len);
919 /* send a control message to retrieve active configuration */
920 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
922 struct linux_device_priv *priv = _device_priv(dev);
923 unsigned char active_config = 0;
926 struct usbfs_ctrltransfer ctrl = {
927 .bmRequestType = LIBUSB_ENDPOINT_IN,
928 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
933 .data = &active_config
936 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
939 return LIBUSB_ERROR_NO_DEVICE;
941 /* we hit this error path frequently with buggy devices :( */
942 usbi_warn(DEVICE_CTX(dev),
943 "get_configuration failed ret=%d errno=%d", r, errno);
944 priv->active_config = -1;
946 if (active_config > 0) {
947 priv->active_config = active_config;
949 /* some buggy devices have a configuration 0, but we're
950 * reaching into the corner of a corner case here, so let's
951 * not support buggy devices in these circumstances.
952 * stick to the specs: a configuration value of 0 means
954 usbi_warn(DEVICE_CTX(dev),
955 "active cfg 0? assuming unconfigured device");
956 priv->active_config = -1;
960 return LIBUSB_SUCCESS;
963 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
964 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
966 struct linux_device_priv *priv = _device_priv(dev);
967 struct libusb_context *ctx = DEVICE_CTX(dev);
968 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
972 dev->bus_number = busnum;
973 dev->device_address = devaddr;
976 priv->sysfs_dir = strdup(sysfs_dir);
977 if (!priv->sysfs_dir)
978 return LIBUSB_ERROR_NO_MEM;
980 /* Note speed can contain 1.5, in this case __read_sysfs_attr
981 will stop parsing at the '.' and return 1 */
982 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
985 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
986 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
987 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
988 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
989 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
991 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
996 /* cache descriptors in memory */
997 if (sysfs_dir && sysfs_has_descriptors) {
998 fd = _open_sysfs_attr(dev, "descriptors");
999 } else if (wrapped_fd < 0) {
1000 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1003 r = lseek(fd, 0, SEEK_SET);
1005 usbi_err(ctx, "seek failed ret=%d errno=%d", r, errno);
1006 return LIBUSB_ERROR_IO;
1013 descriptors_size *= 2;
1014 priv->descriptors = usbi_reallocf(priv->descriptors,
1016 if (!priv->descriptors) {
1017 if (fd != wrapped_fd)
1019 return LIBUSB_ERROR_NO_MEM;
1021 /* usbfs has holes in the file */
1022 if (!(sysfs_dir && sysfs_has_descriptors)) {
1023 memset(priv->descriptors + priv->descriptors_len,
1024 0, descriptors_size - priv->descriptors_len);
1026 r = read(fd, priv->descriptors + priv->descriptors_len,
1027 descriptors_size - priv->descriptors_len);
1029 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1031 if (fd != wrapped_fd)
1033 return LIBUSB_ERROR_IO;
1035 priv->descriptors_len += r;
1036 } while (priv->descriptors_len == descriptors_size);
1038 if (fd != wrapped_fd)
1041 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1042 usbi_err(ctx, "short descriptor read (%d)",
1043 priv->descriptors_len);
1044 return LIBUSB_ERROR_IO;
1047 if (sysfs_dir && sysfs_can_relate_devices)
1048 return LIBUSB_SUCCESS;
1050 /* cache active config */
1052 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1056 /* cannot send a control message to determine the active
1057 * config. just assume the first one is active. */
1058 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1059 "active configuration descriptor");
1060 if (priv->descriptors_len >=
1061 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1062 struct libusb_config_descriptor config;
1063 usbi_parse_descriptor(
1064 priv->descriptors + DEVICE_DESC_LENGTH,
1065 "bbwbbbbb", &config, 0);
1066 priv->active_config = config.bConfigurationValue;
1068 priv->active_config = -1; /* No config dt */
1070 return LIBUSB_SUCCESS;
1073 r = usbfs_get_active_config(dev, fd);
1080 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1082 struct libusb_context *ctx = DEVICE_CTX(dev);
1083 struct libusb_device *it;
1084 char *parent_sysfs_dir, *tmp;
1085 int ret, add_parent = 1;
1087 /* XXX -- can we figure out the topology when using usbfs? */
1088 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1089 /* either using usbfs or finding the parent of a root hub */
1090 return LIBUSB_SUCCESS;
1093 parent_sysfs_dir = strdup(sysfs_dir);
1094 if (NULL == parent_sysfs_dir) {
1095 return LIBUSB_ERROR_NO_MEM;
1097 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1098 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1099 dev->port_number = atoi(tmp + 1);
1102 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1104 free (parent_sysfs_dir);
1105 return LIBUSB_SUCCESS;
1108 /* is the parent a root hub? */
1109 if (NULL == strchr(parent_sysfs_dir, '-')) {
1110 tmp = parent_sysfs_dir;
1111 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1114 return LIBUSB_ERROR_NO_MEM;
1119 /* find the parent in the context */
1120 usbi_mutex_lock(&ctx->usb_devs_lock);
1121 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1122 struct linux_device_priv *priv = _device_priv(it);
1123 if (priv->sysfs_dir) {
1124 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1125 dev->parent_dev = libusb_ref_device(it);
1130 usbi_mutex_unlock(&ctx->usb_devs_lock);
1132 if (!dev->parent_dev && add_parent) {
1133 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1135 sysfs_scan_device(ctx, parent_sysfs_dir);
1140 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1141 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1143 free (parent_sysfs_dir);
1145 return LIBUSB_SUCCESS;
1148 int linux_enumerate_device(struct libusb_context *ctx,
1149 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1151 unsigned long session_id;
1152 struct libusb_device *dev;
1155 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1156 * will be reused. instead we should add a simple sysfs attribute with
1158 session_id = busnum << 8 | devaddr;
1159 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1162 dev = usbi_get_device_by_session_id(ctx, session_id);
1164 /* device already exists in the context */
1165 usbi_dbg("session_id %ld already exists", session_id);
1166 libusb_unref_device(dev);
1167 return LIBUSB_SUCCESS;
1170 usbi_dbg("allocating new device for %d/%d (session %ld)",
1171 busnum, devaddr, session_id);
1172 dev = usbi_alloc_device(ctx, session_id);
1174 return LIBUSB_ERROR_NO_MEM;
1176 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1179 r = usbi_sanitize_device(dev);
1183 r = linux_get_parent_info(dev, sysfs_dir);
1188 libusb_unref_device(dev);
1190 usbi_connect_device(dev);
1195 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1197 struct libusb_context *ctx;
1199 usbi_mutex_static_lock(&active_contexts_lock);
1200 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1201 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1203 usbi_mutex_static_unlock(&active_contexts_lock);
1206 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1208 struct libusb_context *ctx;
1209 struct libusb_device *dev;
1210 unsigned long session_id = busnum << 8 | devaddr;
1212 usbi_mutex_static_lock(&active_contexts_lock);
1213 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1214 dev = usbi_get_device_by_session_id (ctx, session_id);
1216 usbi_disconnect_device (dev);
1217 libusb_unref_device(dev);
1219 usbi_dbg("device not found for session %x", session_id);
1222 usbi_mutex_static_unlock(&active_contexts_lock);
1225 #if !defined(USE_UDEV)
1226 /* open a bus directory and adds all discovered devices to the context */
1227 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1230 char dirpath[PATH_MAX];
1231 struct dirent *entry;
1232 int r = LIBUSB_ERROR_IO;
1234 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1235 usbi_dbg("%s", dirpath);
1236 dir = opendir(dirpath);
1238 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1239 /* FIXME: should handle valid race conditions like hub unplugged
1240 * during directory iteration - this is not an error */
1244 while ((entry = readdir(dir))) {
1247 if (entry->d_name[0] == '.')
1250 devaddr = atoi(entry->d_name);
1252 usbi_dbg("unknown dir entry %s", entry->d_name);
1256 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1257 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1268 static int usbfs_get_device_list(struct libusb_context *ctx)
1270 struct dirent *entry;
1271 DIR *buses = opendir(usbfs_path);
1275 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1276 return LIBUSB_ERROR_IO;
1279 while ((entry = readdir(buses))) {
1282 if (entry->d_name[0] == '.')
1287 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1290 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1292 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1296 busnum = atoi(entry->d_name);
1298 usbi_dbg("unknown dir entry %s", entry->d_name);
1302 r = usbfs_scan_busdir(ctx, busnum);
1314 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1316 uint8_t busnum, devaddr;
1319 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname, -1);
1320 if (LIBUSB_SUCCESS != ret) {
1324 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1328 #if !defined(USE_UDEV)
1329 static int sysfs_get_device_list(struct libusb_context *ctx)
1331 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1332 struct dirent *entry;
1333 int num_devices = 0;
1334 int num_enumerated = 0;
1337 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1338 return LIBUSB_ERROR_IO;
1341 while ((entry = readdir(devices))) {
1342 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1343 || strchr(entry->d_name, ':'))
1348 if (sysfs_scan_device(ctx, entry->d_name)) {
1349 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1358 /* successful if at least one device was enumerated or no devices were found */
1359 if (num_enumerated || !num_devices)
1360 return LIBUSB_SUCCESS;
1362 return LIBUSB_ERROR_IO;
1365 static int linux_default_scan_devices (struct libusb_context *ctx)
1367 /* we can retrieve device list and descriptors from sysfs or usbfs.
1368 * sysfs is preferable, because if we use usbfs we end up resuming
1369 * any autosuspended USB devices. however, sysfs is not available
1370 * everywhere, so we need a usbfs fallback too.
1372 * as described in the "sysfs vs usbfs" comment at the top of this
1373 * file, sometimes we have sysfs but not enough information to
1374 * relate sysfs devices to usbfs nodes. op_init() determines the
1375 * adequacy of sysfs and sets sysfs_can_relate_devices.
1377 if (sysfs_can_relate_devices != 0)
1378 return sysfs_get_device_list(ctx);
1380 return usbfs_get_device_list(ctx);
1384 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1386 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1391 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1393 if (errno == ENOTTY)
1394 usbi_dbg("getcap not available");
1396 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1398 if (supports_flag_zero_packet)
1399 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1400 if (supports_flag_bulk_continuation)
1401 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1404 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1407 static int op_wrap_sys_device(struct libusb_context *ctx,
1408 struct libusb_device_handle *handle, intptr_t sys_dev)
1410 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1411 int fd = (int)sys_dev;
1412 uint8_t busnum, devaddr;
1413 struct usbfs_connectinfo ci;
1414 struct libusb_device *dev;
1417 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1419 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1421 usbi_err(ctx, "connectinfo failed (%d)", errno);
1422 return LIBUSB_ERROR_IO;
1424 /* There is no ioctl to get the bus number. We choose 0 here
1425 * as linux starts numbering buses from 1. */
1427 devaddr = ci.devnum;
1430 /* Session id is unused as we do not add the device to the list of
1431 * connected devices. */
1432 usbi_dbg("allocating new device for fd %d", fd);
1433 dev = usbi_alloc_device(ctx, 0);
1435 return LIBUSB_ERROR_NO_MEM;
1437 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1440 r = usbi_sanitize_device(dev);
1443 /* Consider the device as connected, but do not add it to the managed
1448 r = initialize_handle(handle, fd);
1453 libusb_unref_device(dev);
1457 static int op_open(struct libusb_device_handle *handle)
1461 fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1463 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1464 /* device will still be marked as attached if hotplug monitor thread
1465 * hasn't processed remove event yet */
1466 usbi_mutex_static_lock(&linux_hotplug_lock);
1467 if (handle->dev->attached) {
1468 usbi_dbg("open failed with no device, but device still attached");
1469 linux_device_disconnected(handle->dev->bus_number,
1470 handle->dev->device_address);
1472 usbi_mutex_static_unlock(&linux_hotplug_lock);
1477 r = initialize_handle(handle, fd);
1484 static void op_close(struct libusb_device_handle *dev_handle)
1486 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1487 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1488 if (!hpriv->fd_removed)
1489 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1490 if (!hpriv->fd_keep)
1494 static int op_get_configuration(struct libusb_device_handle *handle,
1497 struct linux_device_priv *priv = _device_priv(handle->dev);
1500 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1501 r = sysfs_get_active_config(handle->dev, config);
1503 r = usbfs_get_active_config(handle->dev,
1504 _device_handle_priv(handle)->fd);
1505 if (r == LIBUSB_SUCCESS)
1506 *config = priv->active_config;
1511 if (*config == -1) {
1512 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1519 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1521 struct linux_device_priv *priv = _device_priv(handle->dev);
1522 int fd = _device_handle_priv(handle)->fd;
1523 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1525 if (errno == EINVAL)
1526 return LIBUSB_ERROR_NOT_FOUND;
1527 else if (errno == EBUSY)
1528 return LIBUSB_ERROR_BUSY;
1529 else if (errno == ENODEV)
1530 return LIBUSB_ERROR_NO_DEVICE;
1532 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1533 return LIBUSB_ERROR_OTHER;
1536 /* update our cached active config descriptor */
1537 priv->active_config = config;
1539 return LIBUSB_SUCCESS;
1542 static int claim_interface(struct libusb_device_handle *handle, int iface)
1544 int fd = _device_handle_priv(handle)->fd;
1545 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1547 if (errno == ENOENT)
1548 return LIBUSB_ERROR_NOT_FOUND;
1549 else if (errno == EBUSY)
1550 return LIBUSB_ERROR_BUSY;
1551 else if (errno == ENODEV)
1552 return LIBUSB_ERROR_NO_DEVICE;
1554 usbi_err(HANDLE_CTX(handle),
1555 "claim interface failed, error %d errno %d", r, errno);
1556 return LIBUSB_ERROR_OTHER;
1561 static int release_interface(struct libusb_device_handle *handle, int iface)
1563 int fd = _device_handle_priv(handle)->fd;
1564 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1566 if (errno == ENODEV)
1567 return LIBUSB_ERROR_NO_DEVICE;
1569 usbi_err(HANDLE_CTX(handle),
1570 "release interface failed, error %d errno %d", r, errno);
1571 return LIBUSB_ERROR_OTHER;
1576 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1579 int fd = _device_handle_priv(handle)->fd;
1580 struct usbfs_setinterface setintf;
1583 setintf.interface = iface;
1584 setintf.altsetting = altsetting;
1585 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1587 if (errno == EINVAL)
1588 return LIBUSB_ERROR_NOT_FOUND;
1589 else if (errno == ENODEV)
1590 return LIBUSB_ERROR_NO_DEVICE;
1592 usbi_err(HANDLE_CTX(handle),
1593 "setintf failed error %d errno %d", r, errno);
1594 return LIBUSB_ERROR_OTHER;
1600 static int op_clear_halt(struct libusb_device_handle *handle,
1601 unsigned char endpoint)
1603 int fd = _device_handle_priv(handle)->fd;
1604 unsigned int _endpoint = endpoint;
1605 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1607 if (errno == ENOENT)
1608 return LIBUSB_ERROR_NOT_FOUND;
1609 else if (errno == ENODEV)
1610 return LIBUSB_ERROR_NO_DEVICE;
1612 usbi_err(HANDLE_CTX(handle),
1613 "clear_halt failed error %d errno %d", r, errno);
1614 return LIBUSB_ERROR_OTHER;
1620 static int op_reset_device(struct libusb_device_handle *handle)
1622 int fd = _device_handle_priv(handle)->fd;
1625 /* Doing a device reset will cause the usbfs driver to get unbound
1626 from any interfaces it is bound to. By voluntarily unbinding
1627 the usbfs driver ourself, we stop the kernel from rebinding
1628 the interface after reset (which would end up with the interface
1629 getting bound to the in kernel driver if any). */
1630 for (i = 0; i < USB_MAXINTERFACES; i++) {
1631 if (handle->claimed_interfaces & (1L << i)) {
1632 release_interface(handle, i);
1636 usbi_mutex_lock(&handle->lock);
1637 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1639 if (errno == ENODEV) {
1640 ret = LIBUSB_ERROR_NOT_FOUND;
1644 usbi_err(HANDLE_CTX(handle),
1645 "reset failed error %d errno %d", r, errno);
1646 ret = LIBUSB_ERROR_OTHER;
1650 /* And re-claim any interfaces which were claimed before the reset */
1651 for (i = 0; i < USB_MAXINTERFACES; i++) {
1652 if (handle->claimed_interfaces & (1L << i)) {
1654 * A driver may have completed modprobing during
1655 * IOCTL_USBFS_RESET, and bound itself as soon as
1656 * IOCTL_USBFS_RESET released the device lock
1658 r = detach_kernel_driver_and_claim(handle, i);
1660 usbi_warn(HANDLE_CTX(handle),
1661 "failed to re-claim interface %d after reset: %s",
1662 i, libusb_error_name(r));
1663 handle->claimed_interfaces &= ~(1L << i);
1664 ret = LIBUSB_ERROR_NOT_FOUND;
1669 usbi_mutex_unlock(&handle->lock);
1673 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1674 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1676 int r, fd = _device_handle_priv(handle)->fd;
1677 struct usbfs_streams *streams;
1679 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1680 return LIBUSB_ERROR_INVALID_PARAM;
1682 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1684 return LIBUSB_ERROR_NO_MEM;
1686 streams->num_streams = num_streams;
1687 streams->num_eps = num_endpoints;
1688 memcpy(streams->eps, endpoints, num_endpoints);
1690 r = ioctl(fd, req, streams);
1695 if (errno == ENOTTY)
1696 return LIBUSB_ERROR_NOT_SUPPORTED;
1697 else if (errno == EINVAL)
1698 return LIBUSB_ERROR_INVALID_PARAM;
1699 else if (errno == ENODEV)
1700 return LIBUSB_ERROR_NO_DEVICE;
1702 usbi_err(HANDLE_CTX(handle),
1703 "streams-ioctl failed error %d errno %d", r, errno);
1704 return LIBUSB_ERROR_OTHER;
1709 static int op_alloc_streams(struct libusb_device_handle *handle,
1710 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1712 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1713 num_streams, endpoints, num_endpoints);
1716 static int op_free_streams(struct libusb_device_handle *handle,
1717 unsigned char *endpoints, int num_endpoints)
1719 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1720 endpoints, num_endpoints);
1723 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1726 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1727 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1728 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1729 if (buffer == MAP_FAILED) {
1730 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1737 static int op_dev_mem_free(struct libusb_device_handle *handle,
1738 unsigned char *buffer, size_t len)
1740 if (munmap(buffer, len) != 0) {
1741 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1743 return LIBUSB_ERROR_OTHER;
1745 return LIBUSB_SUCCESS;
1749 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1752 int fd = _device_handle_priv(handle)->fd;
1753 struct usbfs_getdriver getdrv;
1756 getdrv.interface = interface;
1757 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1759 if (errno == ENODATA)
1761 else if (errno == ENODEV)
1762 return LIBUSB_ERROR_NO_DEVICE;
1764 usbi_err(HANDLE_CTX(handle),
1765 "get driver failed error %d errno %d", r, errno);
1766 return LIBUSB_ERROR_OTHER;
1769 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1772 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1775 int fd = _device_handle_priv(handle)->fd;
1776 struct usbfs_ioctl command;
1777 struct usbfs_getdriver getdrv;
1780 command.ifno = interface;
1781 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1782 command.data = NULL;
1784 getdrv.interface = interface;
1785 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1786 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1787 return LIBUSB_ERROR_NOT_FOUND;
1789 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1791 if (errno == ENODATA)
1792 return LIBUSB_ERROR_NOT_FOUND;
1793 else if (errno == EINVAL)
1794 return LIBUSB_ERROR_INVALID_PARAM;
1795 else if (errno == ENODEV)
1796 return LIBUSB_ERROR_NO_DEVICE;
1798 usbi_err(HANDLE_CTX(handle),
1799 "detach failed error %d errno %d", r, errno);
1800 return LIBUSB_ERROR_OTHER;
1806 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1809 int fd = _device_handle_priv(handle)->fd;
1810 struct usbfs_ioctl command;
1813 command.ifno = interface;
1814 command.ioctl_code = IOCTL_USBFS_CONNECT;
1815 command.data = NULL;
1817 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1819 if (errno == ENODATA)
1820 return LIBUSB_ERROR_NOT_FOUND;
1821 else if (errno == EINVAL)
1822 return LIBUSB_ERROR_INVALID_PARAM;
1823 else if (errno == ENODEV)
1824 return LIBUSB_ERROR_NO_DEVICE;
1825 else if (errno == EBUSY)
1826 return LIBUSB_ERROR_BUSY;
1828 usbi_err(HANDLE_CTX(handle),
1829 "attach failed error %d errno %d", r, errno);
1830 return LIBUSB_ERROR_OTHER;
1831 } else if (r == 0) {
1832 return LIBUSB_ERROR_NOT_FOUND;
1838 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1841 struct usbfs_disconnect_claim dc;
1842 int r, fd = _device_handle_priv(handle)->fd;
1844 dc.interface = interface;
1845 strcpy(dc.driver, "usbfs");
1846 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1847 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1848 if (r != 0 && errno != ENOTTY) {
1851 return LIBUSB_ERROR_BUSY;
1853 return LIBUSB_ERROR_INVALID_PARAM;
1855 return LIBUSB_ERROR_NO_DEVICE;
1857 usbi_err(HANDLE_CTX(handle),
1858 "disconnect-and-claim failed errno %d", errno);
1859 return LIBUSB_ERROR_OTHER;
1863 /* Fallback code for kernels which don't support the
1864 disconnect-and-claim ioctl */
1865 r = op_detach_kernel_driver(handle, interface);
1866 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1869 return claim_interface(handle, interface);
1872 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1874 if (handle->auto_detach_kernel_driver)
1875 return detach_kernel_driver_and_claim(handle, iface);
1877 return claim_interface(handle, iface);
1880 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1884 r = release_interface(handle, iface);
1888 if (handle->auto_detach_kernel_driver)
1889 op_attach_kernel_driver(handle, iface);
1894 static void op_destroy_device(struct libusb_device *dev)
1896 struct linux_device_priv *priv = _device_priv(dev);
1897 if (priv->descriptors)
1898 free(priv->descriptors);
1899 if (priv->sysfs_dir)
1900 free(priv->sysfs_dir);
1903 /* URBs are discarded in reverse order of submission to avoid races. */
1904 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1906 struct libusb_transfer *transfer =
1907 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1908 struct linux_transfer_priv *tpriv =
1909 usbi_transfer_get_os_priv(itransfer);
1910 struct linux_device_handle_priv *dpriv =
1911 _device_handle_priv(transfer->dev_handle);
1913 struct usbfs_urb *urb;
1915 for (i = last_plus_one - 1; i >= first; i--) {
1916 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1917 urb = tpriv->iso_urbs[i];
1919 urb = &tpriv->urbs[i];
1921 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1924 if (EINVAL == errno) {
1925 usbi_dbg("URB not found --> assuming ready to be reaped");
1926 if (i == (last_plus_one - 1))
1927 ret = LIBUSB_ERROR_NOT_FOUND;
1928 } else if (ENODEV == errno) {
1929 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1930 ret = LIBUSB_ERROR_NO_DEVICE;
1932 usbi_warn(TRANSFER_CTX(transfer),
1933 "unrecognised discard errno %d", errno);
1934 ret = LIBUSB_ERROR_OTHER;
1940 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1943 for (i = 0; i < tpriv->num_urbs; i++) {
1944 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1950 free(tpriv->iso_urbs);
1951 tpriv->iso_urbs = NULL;
1954 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1956 struct libusb_transfer *transfer =
1957 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1958 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1959 struct linux_device_handle_priv *dpriv =
1960 _device_handle_priv(transfer->dev_handle);
1961 struct usbfs_urb *urbs;
1962 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1963 == LIBUSB_ENDPOINT_OUT;
1964 int bulk_buffer_len, use_bulk_continuation;
1968 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1969 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1970 return LIBUSB_ERROR_NOT_SUPPORTED;
1973 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1974 * around this by splitting large transfers into 16k blocks, and then
1975 * submit all urbs at once. it would be simpler to submit one urb at
1976 * a time, but there is a big performance gain doing it this way.
1978 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1979 * using arbritary large transfers can still be a bad idea though, as
1980 * the kernel needs to allocate physical contiguous memory for this,
1981 * which may fail for large buffers.
1983 * The kernel solves this problem by splitting the transfer into
1984 * blocks itself when the host-controller is scatter-gather capable
1985 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1987 * Last, there is the issue of short-transfers when splitting, for
1988 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1989 * is needed, but this is not always available.
1991 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1992 /* Good! Just submit everything in one go */
1993 bulk_buffer_len = transfer->length ? transfer->length : 1;
1994 use_bulk_continuation = 0;
1995 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1996 /* Split the transfers and use bulk-continuation to
1997 avoid issues with short-transfers */
1998 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1999 use_bulk_continuation = 1;
2000 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
2001 /* Don't split, assume the kernel can alloc the buffer
2002 (otherwise the submit will fail with -ENOMEM) */
2003 bulk_buffer_len = transfer->length ? transfer->length : 1;
2004 use_bulk_continuation = 0;
2006 /* Bad, splitting without bulk-continuation, short transfers
2007 which end before the last urb will not work reliable! */
2008 /* Note we don't warn here as this is "normal" on kernels <
2009 2.6.32 and not a problem for most applications */
2010 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2011 use_bulk_continuation = 0;
2014 int num_urbs = transfer->length / bulk_buffer_len;
2015 int last_urb_partial = 0;
2017 if (transfer->length == 0) {
2019 } else if ((transfer->length % bulk_buffer_len) > 0) {
2020 last_urb_partial = 1;
2023 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2025 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2027 return LIBUSB_ERROR_NO_MEM;
2029 tpriv->num_urbs = num_urbs;
2030 tpriv->num_retired = 0;
2031 tpriv->reap_action = NORMAL;
2032 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2034 for (i = 0; i < num_urbs; i++) {
2035 struct usbfs_urb *urb = &urbs[i];
2036 urb->usercontext = itransfer;
2037 switch (transfer->type) {
2038 case LIBUSB_TRANSFER_TYPE_BULK:
2039 urb->type = USBFS_URB_TYPE_BULK;
2042 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2043 urb->type = USBFS_URB_TYPE_BULK;
2044 urb->stream_id = itransfer->stream_id;
2046 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2047 urb->type = USBFS_URB_TYPE_INTERRUPT;
2050 urb->endpoint = transfer->endpoint;
2051 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2052 /* don't set the short not ok flag for the last URB */
2053 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2054 urb->flags = USBFS_URB_SHORT_NOT_OK;
2055 if (i == num_urbs - 1 && last_urb_partial)
2056 urb->buffer_length = transfer->length % bulk_buffer_len;
2057 else if (transfer->length == 0)
2058 urb->buffer_length = 0;
2060 urb->buffer_length = bulk_buffer_len;
2062 if (i > 0 && use_bulk_continuation)
2063 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2065 /* we have already checked that the flag is supported */
2066 if (is_out && i == num_urbs - 1 &&
2067 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2068 urb->flags |= USBFS_URB_ZERO_PACKET;
2070 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2072 if (errno == ENODEV) {
2073 r = LIBUSB_ERROR_NO_DEVICE;
2075 usbi_err(TRANSFER_CTX(transfer),
2076 "submiturb failed error %d errno=%d", r, errno);
2077 r = LIBUSB_ERROR_IO;
2080 /* if the first URB submission fails, we can simply free up and
2081 * return failure immediately. */
2083 usbi_dbg("first URB failed, easy peasy");
2089 /* if it's not the first URB that failed, the situation is a bit
2090 * tricky. we may need to discard all previous URBs. there are
2092 * - discarding is asynchronous - discarded urbs will be reaped
2093 * later. the user must not have freed the transfer when the
2094 * discarded URBs are reaped, otherwise libusb will be using
2096 * - the earlier URBs may have completed successfully and we do
2097 * not want to throw away any data.
2098 * - this URB failing may be no error; EREMOTEIO means that
2099 * this transfer simply didn't need all the URBs we submitted
2100 * so, we report that the transfer was submitted successfully and
2101 * in case of error we discard all previous URBs. later when
2102 * the final reap completes we can report error to the user,
2103 * or success if an earlier URB was completed successfully.
2105 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2107 /* The URBs we haven't submitted yet we count as already
2109 tpriv->num_retired += num_urbs - i;
2111 /* If we completed short then don't try to discard. */
2112 if (COMPLETED_EARLY == tpriv->reap_action)
2115 discard_urbs(itransfer, 0, i);
2117 usbi_dbg("reporting successful submission but waiting for %d "
2118 "discards before reporting error", i);
2126 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2128 struct libusb_transfer *transfer =
2129 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2130 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2131 struct linux_device_handle_priv *dpriv =
2132 _device_handle_priv(transfer->dev_handle);
2133 struct usbfs_urb **urbs;
2134 int num_packets = transfer->num_iso_packets;
2135 int num_packets_remaining;
2138 unsigned int packet_len;
2139 unsigned int total_len = 0;
2140 unsigned char *urb_buffer = transfer->buffer;
2142 if (num_packets < 1)
2143 return LIBUSB_ERROR_INVALID_PARAM;
2145 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2146 * at least three times, but we attempt to detect this limit during
2147 * init and check it here. if the kernel rejects the request due to
2148 * its size, we return an error indicating such to the user.
2150 for (i = 0; i < num_packets; i++) {
2151 packet_len = transfer->iso_packet_desc[i].length;
2153 if (packet_len > max_iso_packet_len) {
2154 usbi_warn(TRANSFER_CTX(transfer),
2155 "iso packet length of %u bytes exceeds maximum of %u bytes",
2156 packet_len, max_iso_packet_len);
2157 return LIBUSB_ERROR_INVALID_PARAM;
2160 total_len += packet_len;
2163 if (transfer->length < (int)total_len)
2164 return LIBUSB_ERROR_INVALID_PARAM;
2166 /* usbfs limits the number of iso packets per URB */
2167 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2169 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2172 urbs = calloc(num_urbs, sizeof(*urbs));
2174 return LIBUSB_ERROR_NO_MEM;
2176 tpriv->iso_urbs = urbs;
2177 tpriv->num_urbs = num_urbs;
2178 tpriv->num_retired = 0;
2179 tpriv->reap_action = NORMAL;
2180 tpriv->iso_packet_offset = 0;
2182 /* allocate + initialize each URB with the correct number of packets */
2183 num_packets_remaining = num_packets;
2184 for (i = 0, j = 0; i < num_urbs; i++) {
2185 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2186 struct usbfs_urb *urb;
2190 alloc_size = sizeof(*urb)
2191 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2192 urb = calloc(1, alloc_size);
2194 free_iso_urbs(tpriv);
2195 return LIBUSB_ERROR_NO_MEM;
2199 /* populate packet lengths */
2200 for (k = 0; k < num_packets_in_urb; j++, k++) {
2201 packet_len = transfer->iso_packet_desc[j].length;
2202 urb->buffer_length += packet_len;
2203 urb->iso_frame_desc[k].length = packet_len;
2206 urb->usercontext = itransfer;
2207 urb->type = USBFS_URB_TYPE_ISO;
2208 /* FIXME: interface for non-ASAP data? */
2209 urb->flags = USBFS_URB_ISO_ASAP;
2210 urb->endpoint = transfer->endpoint;
2211 urb->number_of_packets = num_packets_in_urb;
2212 urb->buffer = urb_buffer;
2214 urb_buffer += urb->buffer_length;
2215 num_packets_remaining -= num_packets_in_urb;
2219 for (i = 0; i < num_urbs; i++) {
2220 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2222 if (errno == ENODEV) {
2223 r = LIBUSB_ERROR_NO_DEVICE;
2224 } else if (errno == EINVAL) {
2225 usbi_warn(TRANSFER_CTX(transfer),
2226 "submiturb failed, transfer too large");
2227 r = LIBUSB_ERROR_INVALID_PARAM;
2228 } else if (errno == EMSGSIZE) {
2229 usbi_warn(TRANSFER_CTX(transfer),
2230 "submiturb failed, iso packet length too large");
2231 r = LIBUSB_ERROR_INVALID_PARAM;
2233 usbi_err(TRANSFER_CTX(transfer),
2234 "submiturb failed error %d errno=%d", r, errno);
2235 r = LIBUSB_ERROR_IO;
2238 /* if the first URB submission fails, we can simply free up and
2239 * return failure immediately. */
2241 usbi_dbg("first URB failed, easy peasy");
2242 free_iso_urbs(tpriv);
2246 /* if it's not the first URB that failed, the situation is a bit
2247 * tricky. we must discard all previous URBs. there are
2249 * - discarding is asynchronous - discarded urbs will be reaped
2250 * later. the user must not have freed the transfer when the
2251 * discarded URBs are reaped, otherwise libusb will be using
2253 * - the earlier URBs may have completed successfully and we do
2254 * not want to throw away any data.
2255 * so, in this case we discard all the previous URBs BUT we report
2256 * that the transfer was submitted successfully. then later when
2257 * the final discard completes we can report error to the user.
2259 tpriv->reap_action = SUBMIT_FAILED;
2261 /* The URBs we haven't submitted yet we count as already
2263 tpriv->num_retired = num_urbs - i;
2264 discard_urbs(itransfer, 0, i);
2266 usbi_dbg("reporting successful submission but waiting for %d "
2267 "discards before reporting error", i);
2275 static int submit_control_transfer(struct usbi_transfer *itransfer)
2277 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2278 struct libusb_transfer *transfer =
2279 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2280 struct linux_device_handle_priv *dpriv =
2281 _device_handle_priv(transfer->dev_handle);
2282 struct usbfs_urb *urb;
2285 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2286 return LIBUSB_ERROR_INVALID_PARAM;
2288 urb = calloc(1, sizeof(struct usbfs_urb));
2290 return LIBUSB_ERROR_NO_MEM;
2292 tpriv->num_urbs = 1;
2293 tpriv->reap_action = NORMAL;
2295 urb->usercontext = itransfer;
2296 urb->type = USBFS_URB_TYPE_CONTROL;
2297 urb->endpoint = transfer->endpoint;
2298 urb->buffer = transfer->buffer;
2299 urb->buffer_length = transfer->length;
2301 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2305 if (errno == ENODEV)
2306 return LIBUSB_ERROR_NO_DEVICE;
2308 usbi_err(TRANSFER_CTX(transfer),
2309 "submiturb failed error %d errno=%d", r, errno);
2310 return LIBUSB_ERROR_IO;
2315 static int op_submit_transfer(struct usbi_transfer *itransfer)
2317 struct libusb_transfer *transfer =
2318 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2320 switch (transfer->type) {
2321 case LIBUSB_TRANSFER_TYPE_CONTROL:
2322 return submit_control_transfer(itransfer);
2323 case LIBUSB_TRANSFER_TYPE_BULK:
2324 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2325 return submit_bulk_transfer(itransfer);
2326 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2327 return submit_bulk_transfer(itransfer);
2328 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2329 return submit_iso_transfer(itransfer);
2331 usbi_err(TRANSFER_CTX(transfer),
2332 "unknown endpoint type %d", transfer->type);
2333 return LIBUSB_ERROR_INVALID_PARAM;
2337 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2339 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2340 struct libusb_transfer *transfer =
2341 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2345 return LIBUSB_ERROR_NOT_FOUND;
2347 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2351 switch (transfer->type) {
2352 case LIBUSB_TRANSFER_TYPE_BULK:
2353 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2354 if (tpriv->reap_action == ERROR)
2356 /* else, fall through */
2358 tpriv->reap_action = CANCELLED;
2364 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2366 struct libusb_transfer *transfer =
2367 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2368 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2370 switch (transfer->type) {
2371 case LIBUSB_TRANSFER_TYPE_CONTROL:
2372 case LIBUSB_TRANSFER_TYPE_BULK:
2373 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2374 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2380 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2381 if (tpriv->iso_urbs) {
2382 free_iso_urbs(tpriv);
2383 tpriv->iso_urbs = NULL;
2387 usbi_err(TRANSFER_CTX(transfer),
2388 "unknown endpoint type %d", transfer->type);
2392 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2393 struct usbfs_urb *urb)
2395 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2396 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2397 int urb_idx = urb - tpriv->urbs;
2399 usbi_mutex_lock(&itransfer->lock);
2400 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2401 urb_idx + 1, tpriv->num_urbs);
2403 tpriv->num_retired++;
2405 if (tpriv->reap_action != NORMAL) {
2406 /* cancelled, submit_fail, or completed early */
2407 usbi_dbg("abnormal reap: urb status %d", urb->status);
2409 /* even though we're in the process of cancelling, it's possible that
2410 * we may receive some data in these URBs that we don't want to lose.
2412 * 1. while the kernel is cancelling all the packets that make up an
2413 * URB, a few of them might complete. so we get back a successful
2414 * cancellation *and* some data.
2415 * 2. we receive a short URB which marks the early completion condition,
2416 * so we start cancelling the remaining URBs. however, we're too
2417 * slow and another URB completes (or at least completes partially).
2418 * (this can't happen since we always use BULK_CONTINUATION.)
2420 * When this happens, our objectives are not to lose any "surplus" data,
2421 * and also to stick it at the end of the previously-received data
2422 * (closing any holes), so that libusb reports the total amount of
2423 * transferred data and presents it in a contiguous chunk.
2425 if (urb->actual_length > 0) {
2426 unsigned char *target = transfer->buffer + itransfer->transferred;
2427 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2428 if (urb->buffer != target) {
2429 usbi_dbg("moving surplus data from offset %d to offset %d",
2430 (unsigned char *) urb->buffer - transfer->buffer,
2431 target - transfer->buffer);
2432 memmove(target, urb->buffer, urb->actual_length);
2434 itransfer->transferred += urb->actual_length;
2437 if (tpriv->num_retired == tpriv->num_urbs) {
2438 usbi_dbg("abnormal reap: last URB handled, reporting");
2439 if (tpriv->reap_action != COMPLETED_EARLY &&
2440 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2441 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2447 itransfer->transferred += urb->actual_length;
2449 /* Many of these errors can occur on *any* urb of a multi-urb
2450 * transfer. When they do, we tear down the rest of the transfer.
2452 switch (urb->status) {
2455 case -EREMOTEIO: /* short transfer */
2457 case -ENOENT: /* cancelled */
2462 usbi_dbg("device removed");
2463 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2464 goto cancel_remaining;
2466 usbi_dbg("detected endpoint stall");
2467 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2468 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2469 goto cancel_remaining;
2471 /* overflow can only ever occur in the last urb */
2472 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2473 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2474 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2481 usbi_dbg("low level error %d", urb->status);
2482 tpriv->reap_action = ERROR;
2483 goto cancel_remaining;
2485 usbi_warn(ITRANSFER_CTX(itransfer),
2486 "unrecognised urb status %d", urb->status);
2487 tpriv->reap_action = ERROR;
2488 goto cancel_remaining;
2491 /* if we're the last urb or we got less data than requested then we're
2493 if (urb_idx == tpriv->num_urbs - 1) {
2494 usbi_dbg("last URB in transfer --> complete!");
2496 } else if (urb->actual_length < urb->buffer_length) {
2497 usbi_dbg("short transfer %d/%d --> complete!",
2498 urb->actual_length, urb->buffer_length);
2499 if (tpriv->reap_action == NORMAL)
2500 tpriv->reap_action = COMPLETED_EARLY;
2505 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2506 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2508 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2511 /* cancel remaining urbs and wait for their completion before
2512 * reporting results */
2513 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2516 usbi_mutex_unlock(&itransfer->lock);
2522 usbi_mutex_unlock(&itransfer->lock);
2523 return CANCELLED == tpriv->reap_action ?
2524 usbi_handle_transfer_cancellation(itransfer) :
2525 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2528 static int handle_iso_completion(struct usbi_transfer *itransfer,
2529 struct usbfs_urb *urb)
2531 struct libusb_transfer *transfer =
2532 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2533 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2534 int num_urbs = tpriv->num_urbs;
2537 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2539 usbi_mutex_lock(&itransfer->lock);
2540 for (i = 0; i < num_urbs; i++) {
2541 if (urb == tpriv->iso_urbs[i]) {
2547 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2548 usbi_mutex_unlock(&itransfer->lock);
2549 return LIBUSB_ERROR_NOT_FOUND;
2552 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2555 /* copy isochronous results back in */
2557 for (i = 0; i < urb->number_of_packets; i++) {
2558 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2559 struct libusb_iso_packet_descriptor *lib_desc =
2560 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2561 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2562 switch (urb_desc->status) {
2565 case -ENOENT: /* cancelled */
2570 usbi_dbg("device removed");
2571 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2574 usbi_dbg("detected endpoint stall");
2575 lib_desc->status = LIBUSB_TRANSFER_STALL;
2578 usbi_dbg("overflow error");
2579 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2587 usbi_dbg("low-level USB error %d", urb_desc->status);
2588 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2591 usbi_warn(TRANSFER_CTX(transfer),
2592 "unrecognised urb status %d", urb_desc->status);
2593 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2596 lib_desc->actual_length = urb_desc->actual_length;
2599 tpriv->num_retired++;
2601 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2602 usbi_dbg("CANCEL: urb status %d", urb->status);
2604 if (tpriv->num_retired == num_urbs) {
2605 usbi_dbg("CANCEL: last URB handled, reporting");
2606 free_iso_urbs(tpriv);
2607 if (tpriv->reap_action == CANCELLED) {
2608 usbi_mutex_unlock(&itransfer->lock);
2609 return usbi_handle_transfer_cancellation(itransfer);
2611 usbi_mutex_unlock(&itransfer->lock);
2612 return usbi_handle_transfer_completion(itransfer,
2613 LIBUSB_TRANSFER_ERROR);
2619 switch (urb->status) {
2622 case -ENOENT: /* cancelled */
2626 usbi_dbg("device removed");
2627 status = LIBUSB_TRANSFER_NO_DEVICE;
2630 usbi_warn(TRANSFER_CTX(transfer),
2631 "unrecognised urb status %d", urb->status);
2632 status = LIBUSB_TRANSFER_ERROR;
2636 /* if we're the last urb then we're done */
2637 if (urb_idx == num_urbs) {
2638 usbi_dbg("last URB in transfer --> complete!");
2639 free_iso_urbs(tpriv);
2640 usbi_mutex_unlock(&itransfer->lock);
2641 return usbi_handle_transfer_completion(itransfer, status);
2645 usbi_mutex_unlock(&itransfer->lock);
2649 static int handle_control_completion(struct usbi_transfer *itransfer,
2650 struct usbfs_urb *urb)
2652 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2655 usbi_mutex_lock(&itransfer->lock);
2656 usbi_dbg("handling completion status %d", urb->status);
2658 itransfer->transferred += urb->actual_length;
2660 if (tpriv->reap_action == CANCELLED) {
2661 if (urb->status != 0 && urb->status != -ENOENT)
2662 usbi_warn(ITRANSFER_CTX(itransfer),
2663 "cancel: unrecognised urb status %d", urb->status);
2666 usbi_mutex_unlock(&itransfer->lock);
2667 return usbi_handle_transfer_cancellation(itransfer);
2670 switch (urb->status) {
2672 status = LIBUSB_TRANSFER_COMPLETED;
2674 case -ENOENT: /* cancelled */
2675 status = LIBUSB_TRANSFER_CANCELLED;
2679 usbi_dbg("device removed");
2680 status = LIBUSB_TRANSFER_NO_DEVICE;
2683 usbi_dbg("unsupported control request");
2684 status = LIBUSB_TRANSFER_STALL;
2687 usbi_dbg("control overflow error");
2688 status = LIBUSB_TRANSFER_OVERFLOW;
2695 usbi_dbg("low-level bus error occurred");
2696 status = LIBUSB_TRANSFER_ERROR;
2699 usbi_warn(ITRANSFER_CTX(itransfer),
2700 "unrecognised urb status %d", urb->status);
2701 status = LIBUSB_TRANSFER_ERROR;
2707 usbi_mutex_unlock(&itransfer->lock);
2708 return usbi_handle_transfer_completion(itransfer, status);
2711 static int reap_for_handle(struct libusb_device_handle *handle)
2713 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2715 struct usbfs_urb *urb;
2716 struct usbi_transfer *itransfer;
2717 struct libusb_transfer *transfer;
2719 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2720 if (r == -1 && errno == EAGAIN)
2723 if (errno == ENODEV)
2724 return LIBUSB_ERROR_NO_DEVICE;
2726 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2728 return LIBUSB_ERROR_IO;
2731 itransfer = urb->usercontext;
2732 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2734 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2735 urb->actual_length);
2737 switch (transfer->type) {
2738 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2739 return handle_iso_completion(itransfer, urb);
2740 case LIBUSB_TRANSFER_TYPE_BULK:
2741 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2742 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2743 return handle_bulk_completion(itransfer, urb);
2744 case LIBUSB_TRANSFER_TYPE_CONTROL:
2745 return handle_control_completion(itransfer, urb);
2747 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2749 return LIBUSB_ERROR_OTHER;
2753 static int op_handle_events(struct libusb_context *ctx,
2754 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2759 usbi_mutex_lock(&ctx->open_devs_lock);
2760 for (i = 0; i < nfds && num_ready > 0; i++) {
2761 struct pollfd *pollfd = &fds[i];
2762 struct libusb_device_handle *handle;
2763 struct linux_device_handle_priv *hpriv = NULL;
2765 if (!pollfd->revents)
2769 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2770 hpriv = _device_handle_priv(handle);
2771 if (hpriv->fd == pollfd->fd)
2775 if (!hpriv || hpriv->fd != pollfd->fd) {
2776 usbi_err(ctx, "cannot find handle for fd %d",
2781 if (pollfd->revents & POLLERR) {
2782 /* remove the fd from the pollfd set so that it doesn't continuously
2783 * trigger an event, and flag that it has been removed so op_close()
2784 * doesn't try to remove it a second time */
2785 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2786 hpriv->fd_removed = 1;
2788 /* device will still be marked as attached if hotplug monitor thread
2789 * hasn't processed remove event yet */
2790 usbi_mutex_static_lock(&linux_hotplug_lock);
2791 if (handle->dev->attached)
2792 linux_device_disconnected(handle->dev->bus_number,
2793 handle->dev->device_address);
2794 usbi_mutex_static_unlock(&linux_hotplug_lock);
2796 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2798 r = reap_for_handle(handle);
2802 usbi_handle_disconnect(handle);
2807 r = reap_for_handle(handle);
2809 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2817 usbi_mutex_unlock(&ctx->open_devs_lock);
2821 static int op_clock_gettime(int clk_id, struct timespec *tp)
2824 case USBI_CLOCK_MONOTONIC:
2825 return clock_gettime(monotonic_clkid, tp);
2826 case USBI_CLOCK_REALTIME:
2827 return clock_gettime(CLOCK_REALTIME, tp);
2829 return LIBUSB_ERROR_INVALID_PARAM;
2833 #ifdef USBI_TIMERFD_AVAILABLE
2834 static clockid_t op_get_timerfd_clockid(void)
2836 return monotonic_clkid;
2841 const struct usbi_os_backend usbi_backend = {
2842 .name = "Linux usbfs",
2843 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2846 .get_device_list = NULL,
2847 .hotplug_poll = op_hotplug_poll,
2848 .get_device_descriptor = op_get_device_descriptor,
2849 .get_active_config_descriptor = op_get_active_config_descriptor,
2850 .get_config_descriptor = op_get_config_descriptor,
2851 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2853 .wrap_sys_device = op_wrap_sys_device,
2856 .get_configuration = op_get_configuration,
2857 .set_configuration = op_set_configuration,
2858 .claim_interface = op_claim_interface,
2859 .release_interface = op_release_interface,
2861 .set_interface_altsetting = op_set_interface,
2862 .clear_halt = op_clear_halt,
2863 .reset_device = op_reset_device,
2865 .alloc_streams = op_alloc_streams,
2866 .free_streams = op_free_streams,
2868 .dev_mem_alloc = op_dev_mem_alloc,
2869 .dev_mem_free = op_dev_mem_free,
2871 .kernel_driver_active = op_kernel_driver_active,
2872 .detach_kernel_driver = op_detach_kernel_driver,
2873 .attach_kernel_driver = op_attach_kernel_driver,
2875 .destroy_device = op_destroy_device,
2877 .submit_transfer = op_submit_transfer,
2878 .cancel_transfer = op_cancel_transfer,
2879 .clear_transfer_priv = op_clear_transfer_priv,
2881 .handle_events = op_handle_events,
2883 .clock_gettime = op_clock_gettime,
2885 #ifdef USBI_TIMERFD_AVAILABLE
2886 .get_timerfd_clockid = op_get_timerfd_clockid,
2889 .device_priv_size = sizeof(struct linux_device_priv),
2890 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2891 .transfer_priv_size = sizeof(struct linux_transfer_priv),