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();
537 #elif !defined(__ANDROID__)
538 return linux_netlink_start_event_monitor();
540 return LIBUSB_SUCCESS;
544 static int linux_stop_event_monitor(void)
546 #if defined(USE_UDEV)
547 return linux_udev_stop_event_monitor();
548 #elif !defined(__ANDROID__)
549 return linux_netlink_stop_event_monitor();
551 return LIBUSB_SUCCESS;
555 static int linux_scan_devices(struct libusb_context *ctx)
559 usbi_mutex_static_lock(&linux_hotplug_lock);
561 #if defined(USE_UDEV)
562 ret = linux_udev_scan_devices(ctx);
563 #elif !defined(__ANDROID__)
564 ret = linux_default_scan_devices(ctx);
567 usbi_mutex_static_unlock(&linux_hotplug_lock);
572 static void op_hotplug_poll(void)
574 #if defined(USE_UDEV)
575 linux_udev_hotplug_poll();
576 #elif !defined(__ANDROID__)
577 linux_netlink_hotplug_poll();
581 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
583 struct linux_device_priv *priv = _device_priv(dev);
584 char filename[PATH_MAX];
587 snprintf(filename, PATH_MAX, "%s/%s/%s",
588 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
589 fd = _open(filename, O_RDONLY);
591 usbi_err(DEVICE_CTX(dev),
592 "open %s failed ret=%d errno=%d", filename, fd, errno);
593 return LIBUSB_ERROR_IO;
599 /* Note only suitable for attributes which always read >= 0, < 0 is error */
600 static int __read_sysfs_attr(struct libusb_context *ctx,
601 const char *devname, const char *attr)
603 char filename[PATH_MAX];
607 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
609 fd = _open(filename, O_RDONLY);
611 if (errno == ENOENT) {
612 /* File doesn't exist. Assume the device has been
613 disconnected (see trac ticket #70). */
614 return LIBUSB_ERROR_NO_DEVICE;
616 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
617 return LIBUSB_ERROR_IO;
622 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
624 return LIBUSB_ERROR_OTHER;
627 r = fscanf(f, "%d", &value);
630 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
631 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
634 usbi_err(ctx, "%s contains a negative value", filename);
635 return LIBUSB_ERROR_IO;
641 static int op_get_device_descriptor(struct libusb_device *dev,
642 unsigned char *buffer, int *host_endian)
644 struct linux_device_priv *priv = _device_priv(dev);
646 *host_endian = (priv->sysfs_dir && sysfs_has_descriptors) ? 0 : 1;
647 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
652 /* read the bConfigurationValue for a device */
653 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
656 char tmp[5] = {0, 0, 0, 0, 0};
661 fd = _open_sysfs_attr(dev, "bConfigurationValue");
665 r = read(fd, tmp, sizeof(tmp));
668 usbi_err(DEVICE_CTX(dev),
669 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
670 return LIBUSB_ERROR_IO;
672 usbi_dbg("device unconfigured");
677 if (tmp[sizeof(tmp) - 1] != 0) {
678 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
679 return LIBUSB_ERROR_IO;
680 } else if (tmp[0] == 0) {
681 usbi_err(DEVICE_CTX(dev), "no configuration value?");
682 return LIBUSB_ERROR_IO;
685 num = strtol(tmp, &endptr, 10);
687 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
688 return LIBUSB_ERROR_IO;
695 int linux_get_device_address (struct libusb_context *ctx, int detached,
696 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
697 const char *sys_name, int fd)
699 char proc_path[PATH_MAX], fd_path[PATH_MAX];
703 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
704 /* can't use sysfs to read the bus and device number if the
705 * device has been detached */
706 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
707 if (NULL == dev_node && fd >= 0) {
708 /* try to retrieve the device node from fd */
709 snprintf(proc_path, PATH_MAX, "/proc/self/fd/%d", fd);
710 r = readlink(proc_path, fd_path, PATH_MAX);
714 if (NULL == dev_node) {
715 return LIBUSB_ERROR_OTHER;
718 /* will this work with all supported kernel versions? */
719 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
720 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
721 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
722 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
724 return LIBUSB_ERROR_OTHER;
727 return LIBUSB_SUCCESS;
730 usbi_dbg("scan %s", sys_name);
732 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
735 if (sysfs_attr > 255)
736 return LIBUSB_ERROR_INVALID_PARAM;
737 *busnum = (uint8_t) sysfs_attr;
739 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
742 if (sysfs_attr > 255)
743 return LIBUSB_ERROR_INVALID_PARAM;
745 *devaddr = (uint8_t) sysfs_attr;
747 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
749 return LIBUSB_SUCCESS;
752 /* Return offset of the next descriptor with the given type */
753 static int seek_to_next_descriptor(struct libusb_context *ctx,
754 uint8_t descriptor_type, unsigned char *buffer, int size)
756 struct usb_descriptor_header header;
759 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
761 return LIBUSB_ERROR_NOT_FOUND;
764 usbi_err(ctx, "short descriptor read %d/2", size);
765 return LIBUSB_ERROR_IO;
767 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
769 if (i && header.bDescriptorType == descriptor_type)
772 usbi_err(ctx, "bLength overflow by %d bytes", -size);
773 return LIBUSB_ERROR_IO;
776 /* Return offset to next config */
777 static int seek_to_next_config(struct libusb_device *dev,
778 unsigned char *buffer, int size)
780 struct libusb_context *ctx = DEVICE_CTX(dev);
781 struct linux_device_priv *priv = _device_priv(dev);
782 struct libusb_config_descriptor config;
785 return LIBUSB_ERROR_NOT_FOUND;
787 if (size < LIBUSB_DT_CONFIG_SIZE) {
788 usbi_err(ctx, "short descriptor read %d/%d",
789 size, LIBUSB_DT_CONFIG_SIZE);
790 return LIBUSB_ERROR_IO;
793 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
794 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
795 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
796 config.bDescriptorType);
797 return LIBUSB_ERROR_IO;
801 * In usbfs the config descriptors are config.wTotalLength bytes apart,
802 * with any short reads from the device appearing as holes in the file.
804 * In sysfs wTotalLength is ignored, instead the kernel returns a
805 * config descriptor with verified bLength fields, with descriptors
806 * with an invalid bLength removed.
808 if (priv->sysfs_dir && sysfs_has_descriptors) {
809 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
811 if (next == LIBUSB_ERROR_NOT_FOUND)
816 if (next != config.wTotalLength)
817 usbi_warn(ctx, "config length mismatch wTotalLength "
818 "%d real %d", config.wTotalLength, next);
821 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
822 usbi_err(ctx, "invalid wTotalLength %d",
823 config.wTotalLength);
824 return LIBUSB_ERROR_IO;
825 } else if (config.wTotalLength > size) {
826 usbi_warn(ctx, "short descriptor read %d/%d",
827 size, config.wTotalLength);
830 return config.wTotalLength;
834 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
835 uint8_t value, unsigned char **buffer, int *host_endian)
837 struct linux_device_priv *priv = _device_priv(dev);
838 unsigned char *descriptors = priv->descriptors;
839 int size = priv->descriptors_len;
840 struct libusb_config_descriptor *config;
843 /* Unlike the device desc. config descs. are always in raw format */
846 /* Skip device header */
847 descriptors += DEVICE_DESC_LENGTH;
848 size -= DEVICE_DESC_LENGTH;
850 /* Seek till the config is found, or till "EOF" */
852 int next = seek_to_next_config(dev, descriptors, size);
855 config = (struct libusb_config_descriptor *)descriptors;
856 if (config->bConfigurationValue == value) {
857 *buffer = descriptors;
865 static int op_get_active_config_descriptor(struct libusb_device *dev,
866 unsigned char *buffer, size_t len, int *host_endian)
868 struct linux_device_priv *priv = _device_priv(dev);
870 unsigned char *config_desc;
872 if (priv->sysfs_dir && sysfs_can_relate_devices) {
873 r = sysfs_get_active_config(dev, &config);
877 /* Use cached bConfigurationValue */
878 config = priv->active_config;
881 return LIBUSB_ERROR_NOT_FOUND;
883 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
888 len = MIN(len, (size_t)r);
889 memcpy(buffer, config_desc, len);
893 static int op_get_config_descriptor(struct libusb_device *dev,
894 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
896 struct linux_device_priv *priv = _device_priv(dev);
897 unsigned char *descriptors = priv->descriptors;
898 int i, r, size = priv->descriptors_len;
900 /* Unlike the device desc. config descs. are always in raw format */
903 /* Skip device header */
904 descriptors += DEVICE_DESC_LENGTH;
905 size -= DEVICE_DESC_LENGTH;
907 /* Seek till the config is found, or till "EOF" */
909 r = seek_to_next_config(dev, descriptors, size);
912 if (i == config_index)
918 len = MIN(len, (size_t)r);
919 memcpy(buffer, descriptors, len);
923 /* send a control message to retrieve active configuration */
924 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
926 struct linux_device_priv *priv = _device_priv(dev);
927 unsigned char active_config = 0;
930 struct usbfs_ctrltransfer ctrl = {
931 .bmRequestType = LIBUSB_ENDPOINT_IN,
932 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
937 .data = &active_config
940 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
943 return LIBUSB_ERROR_NO_DEVICE;
945 /* we hit this error path frequently with buggy devices :( */
946 usbi_warn(DEVICE_CTX(dev),
947 "get_configuration failed ret=%d errno=%d", r, errno);
948 priv->active_config = -1;
950 if (active_config > 0) {
951 priv->active_config = active_config;
953 /* some buggy devices have a configuration 0, but we're
954 * reaching into the corner of a corner case here, so let's
955 * not support buggy devices in these circumstances.
956 * stick to the specs: a configuration value of 0 means
958 usbi_warn(DEVICE_CTX(dev),
959 "active cfg 0? assuming unconfigured device");
960 priv->active_config = -1;
964 return LIBUSB_SUCCESS;
967 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
968 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
970 struct linux_device_priv *priv = _device_priv(dev);
971 struct libusb_context *ctx = DEVICE_CTX(dev);
972 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
976 dev->bus_number = busnum;
977 dev->device_address = devaddr;
980 priv->sysfs_dir = strdup(sysfs_dir);
981 if (!priv->sysfs_dir)
982 return LIBUSB_ERROR_NO_MEM;
984 /* Note speed can contain 1.5, in this case __read_sysfs_attr
985 will stop parsing at the '.' and return 1 */
986 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
989 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
990 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
991 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
992 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
993 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
995 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
1000 /* cache descriptors in memory */
1001 if (sysfs_dir && sysfs_has_descriptors) {
1002 fd = _open_sysfs_attr(dev, "descriptors");
1003 } else if (wrapped_fd < 0) {
1004 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1007 r = lseek(fd, 0, SEEK_SET);
1009 usbi_err(ctx, "seek failed ret=%d errno=%d", r, errno);
1010 return LIBUSB_ERROR_IO;
1017 descriptors_size *= 2;
1018 priv->descriptors = usbi_reallocf(priv->descriptors,
1020 if (!priv->descriptors) {
1021 if (fd != wrapped_fd)
1023 return LIBUSB_ERROR_NO_MEM;
1025 /* usbfs has holes in the file */
1026 if (!(sysfs_dir && sysfs_has_descriptors)) {
1027 memset(priv->descriptors + priv->descriptors_len,
1028 0, descriptors_size - priv->descriptors_len);
1030 r = read(fd, priv->descriptors + priv->descriptors_len,
1031 descriptors_size - priv->descriptors_len);
1033 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1035 if (fd != wrapped_fd)
1037 return LIBUSB_ERROR_IO;
1039 priv->descriptors_len += r;
1040 } while (priv->descriptors_len == descriptors_size);
1042 if (fd != wrapped_fd)
1045 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1046 usbi_err(ctx, "short descriptor read (%d)",
1047 priv->descriptors_len);
1048 return LIBUSB_ERROR_IO;
1051 if (sysfs_dir && sysfs_can_relate_devices)
1052 return LIBUSB_SUCCESS;
1054 /* cache active config */
1056 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1060 /* cannot send a control message to determine the active
1061 * config. just assume the first one is active. */
1062 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1063 "active configuration descriptor");
1064 if (priv->descriptors_len >=
1065 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1066 struct libusb_config_descriptor config;
1067 usbi_parse_descriptor(
1068 priv->descriptors + DEVICE_DESC_LENGTH,
1069 "bbwbbbbb", &config, 0);
1070 priv->active_config = config.bConfigurationValue;
1072 priv->active_config = -1; /* No config dt */
1074 return LIBUSB_SUCCESS;
1077 r = usbfs_get_active_config(dev, fd);
1084 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1086 struct libusb_context *ctx = DEVICE_CTX(dev);
1087 struct libusb_device *it;
1088 char *parent_sysfs_dir, *tmp;
1089 int ret, add_parent = 1;
1091 /* XXX -- can we figure out the topology when using usbfs? */
1092 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1093 /* either using usbfs or finding the parent of a root hub */
1094 return LIBUSB_SUCCESS;
1097 parent_sysfs_dir = strdup(sysfs_dir);
1098 if (NULL == parent_sysfs_dir) {
1099 return LIBUSB_ERROR_NO_MEM;
1101 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1102 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1103 dev->port_number = atoi(tmp + 1);
1106 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1108 free (parent_sysfs_dir);
1109 return LIBUSB_SUCCESS;
1112 /* is the parent a root hub? */
1113 if (NULL == strchr(parent_sysfs_dir, '-')) {
1114 tmp = parent_sysfs_dir;
1115 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1118 return LIBUSB_ERROR_NO_MEM;
1123 /* find the parent in the context */
1124 usbi_mutex_lock(&ctx->usb_devs_lock);
1125 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1126 struct linux_device_priv *priv = _device_priv(it);
1127 if (priv->sysfs_dir) {
1128 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1129 dev->parent_dev = libusb_ref_device(it);
1134 usbi_mutex_unlock(&ctx->usb_devs_lock);
1136 if (!dev->parent_dev && add_parent) {
1137 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1139 sysfs_scan_device(ctx, parent_sysfs_dir);
1144 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1145 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1147 free (parent_sysfs_dir);
1149 return LIBUSB_SUCCESS;
1152 int linux_enumerate_device(struct libusb_context *ctx,
1153 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1155 unsigned long session_id;
1156 struct libusb_device *dev;
1159 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1160 * will be reused. instead we should add a simple sysfs attribute with
1162 session_id = busnum << 8 | devaddr;
1163 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1166 dev = usbi_get_device_by_session_id(ctx, session_id);
1168 /* device already exists in the context */
1169 usbi_dbg("session_id %ld already exists", session_id);
1170 libusb_unref_device(dev);
1171 return LIBUSB_SUCCESS;
1174 usbi_dbg("allocating new device for %d/%d (session %ld)",
1175 busnum, devaddr, session_id);
1176 dev = usbi_alloc_device(ctx, session_id);
1178 return LIBUSB_ERROR_NO_MEM;
1180 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1183 r = usbi_sanitize_device(dev);
1187 r = linux_get_parent_info(dev, sysfs_dir);
1192 libusb_unref_device(dev);
1194 usbi_connect_device(dev);
1199 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1201 struct libusb_context *ctx;
1203 usbi_mutex_static_lock(&active_contexts_lock);
1204 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1205 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1207 usbi_mutex_static_unlock(&active_contexts_lock);
1210 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1212 struct libusb_context *ctx;
1213 struct libusb_device *dev;
1214 unsigned long session_id = busnum << 8 | devaddr;
1216 usbi_mutex_static_lock(&active_contexts_lock);
1217 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1218 dev = usbi_get_device_by_session_id (ctx, session_id);
1220 usbi_disconnect_device (dev);
1221 libusb_unref_device(dev);
1223 usbi_dbg("device not found for session %x", session_id);
1226 usbi_mutex_static_unlock(&active_contexts_lock);
1229 #if !defined(USE_UDEV)
1230 /* open a bus directory and adds all discovered devices to the context */
1231 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1234 char dirpath[PATH_MAX];
1235 struct dirent *entry;
1236 int r = LIBUSB_ERROR_IO;
1238 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1239 usbi_dbg("%s", dirpath);
1240 dir = opendir(dirpath);
1242 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1243 /* FIXME: should handle valid race conditions like hub unplugged
1244 * during directory iteration - this is not an error */
1248 while ((entry = readdir(dir))) {
1251 if (entry->d_name[0] == '.')
1254 devaddr = atoi(entry->d_name);
1256 usbi_dbg("unknown dir entry %s", entry->d_name);
1260 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1261 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1272 static int usbfs_get_device_list(struct libusb_context *ctx)
1274 struct dirent *entry;
1275 DIR *buses = opendir(usbfs_path);
1279 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1280 return LIBUSB_ERROR_IO;
1283 while ((entry = readdir(buses))) {
1286 if (entry->d_name[0] == '.')
1291 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1294 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1296 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1300 busnum = atoi(entry->d_name);
1302 usbi_dbg("unknown dir entry %s", entry->d_name);
1306 r = usbfs_scan_busdir(ctx, busnum);
1318 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1320 uint8_t busnum, devaddr;
1323 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname, -1);
1324 if (LIBUSB_SUCCESS != ret) {
1328 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1332 #if !defined(USE_UDEV)
1333 static int sysfs_get_device_list(struct libusb_context *ctx)
1335 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1336 struct dirent *entry;
1337 int num_devices = 0;
1338 int num_enumerated = 0;
1341 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1342 return LIBUSB_ERROR_IO;
1345 while ((entry = readdir(devices))) {
1346 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1347 || strchr(entry->d_name, ':'))
1352 if (sysfs_scan_device(ctx, entry->d_name)) {
1353 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1362 /* successful if at least one device was enumerated or no devices were found */
1363 if (num_enumerated || !num_devices)
1364 return LIBUSB_SUCCESS;
1366 return LIBUSB_ERROR_IO;
1369 static int linux_default_scan_devices (struct libusb_context *ctx)
1371 /* we can retrieve device list and descriptors from sysfs or usbfs.
1372 * sysfs is preferable, because if we use usbfs we end up resuming
1373 * any autosuspended USB devices. however, sysfs is not available
1374 * everywhere, so we need a usbfs fallback too.
1376 * as described in the "sysfs vs usbfs" comment at the top of this
1377 * file, sometimes we have sysfs but not enough information to
1378 * relate sysfs devices to usbfs nodes. op_init() determines the
1379 * adequacy of sysfs and sets sysfs_can_relate_devices.
1381 if (sysfs_can_relate_devices != 0)
1382 return sysfs_get_device_list(ctx);
1384 return usbfs_get_device_list(ctx);
1388 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1390 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1395 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1397 if (errno == ENOTTY)
1398 usbi_dbg("getcap not available");
1400 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1402 if (supports_flag_zero_packet)
1403 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1404 if (supports_flag_bulk_continuation)
1405 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1408 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1411 static int op_wrap_sys_device(struct libusb_context *ctx,
1412 struct libusb_device_handle *handle, intptr_t sys_dev)
1414 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1415 int fd = (int)sys_dev;
1416 uint8_t busnum, devaddr;
1417 struct usbfs_connectinfo ci;
1418 struct libusb_device *dev;
1421 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1423 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1425 usbi_err(ctx, "connectinfo failed (%d)", errno);
1426 return LIBUSB_ERROR_IO;
1428 /* There is no ioctl to get the bus number. We choose 0 here
1429 * as linux starts numbering buses from 1. */
1431 devaddr = ci.devnum;
1434 /* Session id is unused as we do not add the device to the list of
1435 * connected devices. */
1436 usbi_dbg("allocating new device for fd %d", fd);
1437 dev = usbi_alloc_device(ctx, 0);
1439 return LIBUSB_ERROR_NO_MEM;
1441 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1444 r = usbi_sanitize_device(dev);
1447 /* Consider the device as connected, but do not add it to the managed
1452 r = initialize_handle(handle, fd);
1457 libusb_unref_device(dev);
1461 static int op_open(struct libusb_device_handle *handle)
1465 fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1467 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1468 /* device will still be marked as attached if hotplug monitor thread
1469 * hasn't processed remove event yet */
1470 usbi_mutex_static_lock(&linux_hotplug_lock);
1471 if (handle->dev->attached) {
1472 usbi_dbg("open failed with no device, but device still attached");
1473 linux_device_disconnected(handle->dev->bus_number,
1474 handle->dev->device_address);
1476 usbi_mutex_static_unlock(&linux_hotplug_lock);
1481 r = initialize_handle(handle, fd);
1488 static void op_close(struct libusb_device_handle *dev_handle)
1490 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1491 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1492 if (!hpriv->fd_removed)
1493 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1494 if (!hpriv->fd_keep)
1498 static int op_get_configuration(struct libusb_device_handle *handle,
1501 struct linux_device_priv *priv = _device_priv(handle->dev);
1504 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1505 r = sysfs_get_active_config(handle->dev, config);
1507 r = usbfs_get_active_config(handle->dev,
1508 _device_handle_priv(handle)->fd);
1509 if (r == LIBUSB_SUCCESS)
1510 *config = priv->active_config;
1515 if (*config == -1) {
1516 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1523 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1525 struct linux_device_priv *priv = _device_priv(handle->dev);
1526 int fd = _device_handle_priv(handle)->fd;
1527 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1529 if (errno == EINVAL)
1530 return LIBUSB_ERROR_NOT_FOUND;
1531 else if (errno == EBUSY)
1532 return LIBUSB_ERROR_BUSY;
1533 else if (errno == ENODEV)
1534 return LIBUSB_ERROR_NO_DEVICE;
1536 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1537 return LIBUSB_ERROR_OTHER;
1540 /* update our cached active config descriptor */
1541 priv->active_config = config;
1543 return LIBUSB_SUCCESS;
1546 static int claim_interface(struct libusb_device_handle *handle, int iface)
1548 int fd = _device_handle_priv(handle)->fd;
1549 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1551 if (errno == ENOENT)
1552 return LIBUSB_ERROR_NOT_FOUND;
1553 else if (errno == EBUSY)
1554 return LIBUSB_ERROR_BUSY;
1555 else if (errno == ENODEV)
1556 return LIBUSB_ERROR_NO_DEVICE;
1558 usbi_err(HANDLE_CTX(handle),
1559 "claim interface failed, error %d errno %d", r, errno);
1560 return LIBUSB_ERROR_OTHER;
1565 static int release_interface(struct libusb_device_handle *handle, int iface)
1567 int fd = _device_handle_priv(handle)->fd;
1568 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1570 if (errno == ENODEV)
1571 return LIBUSB_ERROR_NO_DEVICE;
1573 usbi_err(HANDLE_CTX(handle),
1574 "release interface failed, error %d errno %d", r, errno);
1575 return LIBUSB_ERROR_OTHER;
1580 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1583 int fd = _device_handle_priv(handle)->fd;
1584 struct usbfs_setinterface setintf;
1587 setintf.interface = iface;
1588 setintf.altsetting = altsetting;
1589 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1591 if (errno == EINVAL)
1592 return LIBUSB_ERROR_NOT_FOUND;
1593 else if (errno == ENODEV)
1594 return LIBUSB_ERROR_NO_DEVICE;
1596 usbi_err(HANDLE_CTX(handle),
1597 "setintf failed error %d errno %d", r, errno);
1598 return LIBUSB_ERROR_OTHER;
1604 static int op_clear_halt(struct libusb_device_handle *handle,
1605 unsigned char endpoint)
1607 int fd = _device_handle_priv(handle)->fd;
1608 unsigned int _endpoint = endpoint;
1609 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1611 if (errno == ENOENT)
1612 return LIBUSB_ERROR_NOT_FOUND;
1613 else if (errno == ENODEV)
1614 return LIBUSB_ERROR_NO_DEVICE;
1616 usbi_err(HANDLE_CTX(handle),
1617 "clear_halt failed error %d errno %d", r, errno);
1618 return LIBUSB_ERROR_OTHER;
1624 static int op_reset_device(struct libusb_device_handle *handle)
1626 int fd = _device_handle_priv(handle)->fd;
1629 /* Doing a device reset will cause the usbfs driver to get unbound
1630 from any interfaces it is bound to. By voluntarily unbinding
1631 the usbfs driver ourself, we stop the kernel from rebinding
1632 the interface after reset (which would end up with the interface
1633 getting bound to the in kernel driver if any). */
1634 for (i = 0; i < USB_MAXINTERFACES; i++) {
1635 if (handle->claimed_interfaces & (1L << i)) {
1636 release_interface(handle, i);
1640 usbi_mutex_lock(&handle->lock);
1641 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1643 if (errno == ENODEV) {
1644 ret = LIBUSB_ERROR_NOT_FOUND;
1648 usbi_err(HANDLE_CTX(handle),
1649 "reset failed error %d errno %d", r, errno);
1650 ret = LIBUSB_ERROR_OTHER;
1654 /* And re-claim any interfaces which were claimed before the reset */
1655 for (i = 0; i < USB_MAXINTERFACES; i++) {
1656 if (handle->claimed_interfaces & (1L << i)) {
1658 * A driver may have completed modprobing during
1659 * IOCTL_USBFS_RESET, and bound itself as soon as
1660 * IOCTL_USBFS_RESET released the device lock
1662 r = detach_kernel_driver_and_claim(handle, i);
1664 usbi_warn(HANDLE_CTX(handle),
1665 "failed to re-claim interface %d after reset: %s",
1666 i, libusb_error_name(r));
1667 handle->claimed_interfaces &= ~(1L << i);
1668 ret = LIBUSB_ERROR_NOT_FOUND;
1673 usbi_mutex_unlock(&handle->lock);
1677 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1678 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1680 int r, fd = _device_handle_priv(handle)->fd;
1681 struct usbfs_streams *streams;
1683 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1684 return LIBUSB_ERROR_INVALID_PARAM;
1686 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1688 return LIBUSB_ERROR_NO_MEM;
1690 streams->num_streams = num_streams;
1691 streams->num_eps = num_endpoints;
1692 memcpy(streams->eps, endpoints, num_endpoints);
1694 r = ioctl(fd, req, streams);
1699 if (errno == ENOTTY)
1700 return LIBUSB_ERROR_NOT_SUPPORTED;
1701 else if (errno == EINVAL)
1702 return LIBUSB_ERROR_INVALID_PARAM;
1703 else if (errno == ENODEV)
1704 return LIBUSB_ERROR_NO_DEVICE;
1706 usbi_err(HANDLE_CTX(handle),
1707 "streams-ioctl failed error %d errno %d", r, errno);
1708 return LIBUSB_ERROR_OTHER;
1713 static int op_alloc_streams(struct libusb_device_handle *handle,
1714 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1716 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1717 num_streams, endpoints, num_endpoints);
1720 static int op_free_streams(struct libusb_device_handle *handle,
1721 unsigned char *endpoints, int num_endpoints)
1723 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1724 endpoints, num_endpoints);
1727 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1730 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1731 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1732 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1733 if (buffer == MAP_FAILED) {
1734 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1741 static int op_dev_mem_free(struct libusb_device_handle *handle,
1742 unsigned char *buffer, size_t len)
1744 if (munmap(buffer, len) != 0) {
1745 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1747 return LIBUSB_ERROR_OTHER;
1749 return LIBUSB_SUCCESS;
1753 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1756 int fd = _device_handle_priv(handle)->fd;
1757 struct usbfs_getdriver getdrv;
1760 getdrv.interface = interface;
1761 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1763 if (errno == ENODATA)
1765 else if (errno == ENODEV)
1766 return LIBUSB_ERROR_NO_DEVICE;
1768 usbi_err(HANDLE_CTX(handle),
1769 "get driver failed error %d errno %d", r, errno);
1770 return LIBUSB_ERROR_OTHER;
1773 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1776 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1779 int fd = _device_handle_priv(handle)->fd;
1780 struct usbfs_ioctl command;
1781 struct usbfs_getdriver getdrv;
1784 command.ifno = interface;
1785 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1786 command.data = NULL;
1788 getdrv.interface = interface;
1789 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1790 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1791 return LIBUSB_ERROR_NOT_FOUND;
1793 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1795 if (errno == ENODATA)
1796 return LIBUSB_ERROR_NOT_FOUND;
1797 else if (errno == EINVAL)
1798 return LIBUSB_ERROR_INVALID_PARAM;
1799 else if (errno == ENODEV)
1800 return LIBUSB_ERROR_NO_DEVICE;
1802 usbi_err(HANDLE_CTX(handle),
1803 "detach failed error %d errno %d", r, errno);
1804 return LIBUSB_ERROR_OTHER;
1810 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1813 int fd = _device_handle_priv(handle)->fd;
1814 struct usbfs_ioctl command;
1817 command.ifno = interface;
1818 command.ioctl_code = IOCTL_USBFS_CONNECT;
1819 command.data = NULL;
1821 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1823 if (errno == ENODATA)
1824 return LIBUSB_ERROR_NOT_FOUND;
1825 else if (errno == EINVAL)
1826 return LIBUSB_ERROR_INVALID_PARAM;
1827 else if (errno == ENODEV)
1828 return LIBUSB_ERROR_NO_DEVICE;
1829 else if (errno == EBUSY)
1830 return LIBUSB_ERROR_BUSY;
1832 usbi_err(HANDLE_CTX(handle),
1833 "attach failed error %d errno %d", r, errno);
1834 return LIBUSB_ERROR_OTHER;
1835 } else if (r == 0) {
1836 return LIBUSB_ERROR_NOT_FOUND;
1842 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1845 struct usbfs_disconnect_claim dc;
1846 int r, fd = _device_handle_priv(handle)->fd;
1848 dc.interface = interface;
1849 strcpy(dc.driver, "usbfs");
1850 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1851 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1852 if (r != 0 && errno != ENOTTY) {
1855 return LIBUSB_ERROR_BUSY;
1857 return LIBUSB_ERROR_INVALID_PARAM;
1859 return LIBUSB_ERROR_NO_DEVICE;
1861 usbi_err(HANDLE_CTX(handle),
1862 "disconnect-and-claim failed errno %d", errno);
1863 return LIBUSB_ERROR_OTHER;
1867 /* Fallback code for kernels which don't support the
1868 disconnect-and-claim ioctl */
1869 r = op_detach_kernel_driver(handle, interface);
1870 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1873 return claim_interface(handle, interface);
1876 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1878 if (handle->auto_detach_kernel_driver)
1879 return detach_kernel_driver_and_claim(handle, iface);
1881 return claim_interface(handle, iface);
1884 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1888 r = release_interface(handle, iface);
1892 if (handle->auto_detach_kernel_driver)
1893 op_attach_kernel_driver(handle, iface);
1898 static void op_destroy_device(struct libusb_device *dev)
1900 struct linux_device_priv *priv = _device_priv(dev);
1901 if (priv->descriptors)
1902 free(priv->descriptors);
1903 if (priv->sysfs_dir)
1904 free(priv->sysfs_dir);
1907 /* URBs are discarded in reverse order of submission to avoid races. */
1908 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1910 struct libusb_transfer *transfer =
1911 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1912 struct linux_transfer_priv *tpriv =
1913 usbi_transfer_get_os_priv(itransfer);
1914 struct linux_device_handle_priv *dpriv =
1915 _device_handle_priv(transfer->dev_handle);
1917 struct usbfs_urb *urb;
1919 for (i = last_plus_one - 1; i >= first; i--) {
1920 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1921 urb = tpriv->iso_urbs[i];
1923 urb = &tpriv->urbs[i];
1925 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1928 if (EINVAL == errno) {
1929 usbi_dbg("URB not found --> assuming ready to be reaped");
1930 if (i == (last_plus_one - 1))
1931 ret = LIBUSB_ERROR_NOT_FOUND;
1932 } else if (ENODEV == errno) {
1933 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1934 ret = LIBUSB_ERROR_NO_DEVICE;
1936 usbi_warn(TRANSFER_CTX(transfer),
1937 "unrecognised discard errno %d", errno);
1938 ret = LIBUSB_ERROR_OTHER;
1944 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1947 for (i = 0; i < tpriv->num_urbs; i++) {
1948 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1954 free(tpriv->iso_urbs);
1955 tpriv->iso_urbs = NULL;
1958 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1960 struct libusb_transfer *transfer =
1961 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1962 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1963 struct linux_device_handle_priv *dpriv =
1964 _device_handle_priv(transfer->dev_handle);
1965 struct usbfs_urb *urbs;
1966 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1967 == LIBUSB_ENDPOINT_OUT;
1968 int bulk_buffer_len, use_bulk_continuation;
1972 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1973 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1974 return LIBUSB_ERROR_NOT_SUPPORTED;
1977 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1978 * around this by splitting large transfers into 16k blocks, and then
1979 * submit all urbs at once. it would be simpler to submit one urb at
1980 * a time, but there is a big performance gain doing it this way.
1982 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1983 * using arbritary large transfers can still be a bad idea though, as
1984 * the kernel needs to allocate physical contiguous memory for this,
1985 * which may fail for large buffers.
1987 * The kernel solves this problem by splitting the transfer into
1988 * blocks itself when the host-controller is scatter-gather capable
1989 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1991 * Last, there is the issue of short-transfers when splitting, for
1992 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1993 * is needed, but this is not always available.
1995 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1996 /* Good! Just submit everything in one go */
1997 bulk_buffer_len = transfer->length ? transfer->length : 1;
1998 use_bulk_continuation = 0;
1999 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
2000 /* Split the transfers and use bulk-continuation to
2001 avoid issues with short-transfers */
2002 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2003 use_bulk_continuation = 1;
2004 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
2005 /* Don't split, assume the kernel can alloc the buffer
2006 (otherwise the submit will fail with -ENOMEM) */
2007 bulk_buffer_len = transfer->length ? transfer->length : 1;
2008 use_bulk_continuation = 0;
2010 /* Bad, splitting without bulk-continuation, short transfers
2011 which end before the last urb will not work reliable! */
2012 /* Note we don't warn here as this is "normal" on kernels <
2013 2.6.32 and not a problem for most applications */
2014 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2015 use_bulk_continuation = 0;
2018 int num_urbs = transfer->length / bulk_buffer_len;
2019 int last_urb_partial = 0;
2021 if (transfer->length == 0) {
2023 } else if ((transfer->length % bulk_buffer_len) > 0) {
2024 last_urb_partial = 1;
2027 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2029 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2031 return LIBUSB_ERROR_NO_MEM;
2033 tpriv->num_urbs = num_urbs;
2034 tpriv->num_retired = 0;
2035 tpriv->reap_action = NORMAL;
2036 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2038 for (i = 0; i < num_urbs; i++) {
2039 struct usbfs_urb *urb = &urbs[i];
2040 urb->usercontext = itransfer;
2041 switch (transfer->type) {
2042 case LIBUSB_TRANSFER_TYPE_BULK:
2043 urb->type = USBFS_URB_TYPE_BULK;
2046 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2047 urb->type = USBFS_URB_TYPE_BULK;
2048 urb->stream_id = itransfer->stream_id;
2050 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2051 urb->type = USBFS_URB_TYPE_INTERRUPT;
2054 urb->endpoint = transfer->endpoint;
2055 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2056 /* don't set the short not ok flag for the last URB */
2057 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2058 urb->flags = USBFS_URB_SHORT_NOT_OK;
2059 if (i == num_urbs - 1 && last_urb_partial)
2060 urb->buffer_length = transfer->length % bulk_buffer_len;
2061 else if (transfer->length == 0)
2062 urb->buffer_length = 0;
2064 urb->buffer_length = bulk_buffer_len;
2066 if (i > 0 && use_bulk_continuation)
2067 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2069 /* we have already checked that the flag is supported */
2070 if (is_out && i == num_urbs - 1 &&
2071 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2072 urb->flags |= USBFS_URB_ZERO_PACKET;
2074 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2076 if (errno == ENODEV) {
2077 r = LIBUSB_ERROR_NO_DEVICE;
2079 usbi_err(TRANSFER_CTX(transfer),
2080 "submiturb failed error %d errno=%d", r, errno);
2081 r = LIBUSB_ERROR_IO;
2084 /* if the first URB submission fails, we can simply free up and
2085 * return failure immediately. */
2087 usbi_dbg("first URB failed, easy peasy");
2093 /* if it's not the first URB that failed, the situation is a bit
2094 * tricky. we may need to discard all previous URBs. there are
2096 * - discarding is asynchronous - discarded urbs will be reaped
2097 * later. the user must not have freed the transfer when the
2098 * discarded URBs are reaped, otherwise libusb will be using
2100 * - the earlier URBs may have completed successfully and we do
2101 * not want to throw away any data.
2102 * - this URB failing may be no error; EREMOTEIO means that
2103 * this transfer simply didn't need all the URBs we submitted
2104 * so, we report that the transfer was submitted successfully and
2105 * in case of error we discard all previous URBs. later when
2106 * the final reap completes we can report error to the user,
2107 * or success if an earlier URB was completed successfully.
2109 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2111 /* The URBs we haven't submitted yet we count as already
2113 tpriv->num_retired += num_urbs - i;
2115 /* If we completed short then don't try to discard. */
2116 if (COMPLETED_EARLY == tpriv->reap_action)
2119 discard_urbs(itransfer, 0, i);
2121 usbi_dbg("reporting successful submission but waiting for %d "
2122 "discards before reporting error", i);
2130 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2132 struct libusb_transfer *transfer =
2133 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2134 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2135 struct linux_device_handle_priv *dpriv =
2136 _device_handle_priv(transfer->dev_handle);
2137 struct usbfs_urb **urbs;
2138 int num_packets = transfer->num_iso_packets;
2139 int num_packets_remaining;
2142 unsigned int packet_len;
2143 unsigned int total_len = 0;
2144 unsigned char *urb_buffer = transfer->buffer;
2146 if (num_packets < 1)
2147 return LIBUSB_ERROR_INVALID_PARAM;
2149 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2150 * at least three times, but we attempt to detect this limit during
2151 * init and check it here. if the kernel rejects the request due to
2152 * its size, we return an error indicating such to the user.
2154 for (i = 0; i < num_packets; i++) {
2155 packet_len = transfer->iso_packet_desc[i].length;
2157 if (packet_len > max_iso_packet_len) {
2158 usbi_warn(TRANSFER_CTX(transfer),
2159 "iso packet length of %u bytes exceeds maximum of %u bytes",
2160 packet_len, max_iso_packet_len);
2161 return LIBUSB_ERROR_INVALID_PARAM;
2164 total_len += packet_len;
2167 if (transfer->length < (int)total_len)
2168 return LIBUSB_ERROR_INVALID_PARAM;
2170 /* usbfs limits the number of iso packets per URB */
2171 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2173 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2176 urbs = calloc(num_urbs, sizeof(*urbs));
2178 return LIBUSB_ERROR_NO_MEM;
2180 tpriv->iso_urbs = urbs;
2181 tpriv->num_urbs = num_urbs;
2182 tpriv->num_retired = 0;
2183 tpriv->reap_action = NORMAL;
2184 tpriv->iso_packet_offset = 0;
2186 /* allocate + initialize each URB with the correct number of packets */
2187 num_packets_remaining = num_packets;
2188 for (i = 0, j = 0; i < num_urbs; i++) {
2189 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2190 struct usbfs_urb *urb;
2194 alloc_size = sizeof(*urb)
2195 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2196 urb = calloc(1, alloc_size);
2198 free_iso_urbs(tpriv);
2199 return LIBUSB_ERROR_NO_MEM;
2203 /* populate packet lengths */
2204 for (k = 0; k < num_packets_in_urb; j++, k++) {
2205 packet_len = transfer->iso_packet_desc[j].length;
2206 urb->buffer_length += packet_len;
2207 urb->iso_frame_desc[k].length = packet_len;
2210 urb->usercontext = itransfer;
2211 urb->type = USBFS_URB_TYPE_ISO;
2212 /* FIXME: interface for non-ASAP data? */
2213 urb->flags = USBFS_URB_ISO_ASAP;
2214 urb->endpoint = transfer->endpoint;
2215 urb->number_of_packets = num_packets_in_urb;
2216 urb->buffer = urb_buffer;
2218 urb_buffer += urb->buffer_length;
2219 num_packets_remaining -= num_packets_in_urb;
2223 for (i = 0; i < num_urbs; i++) {
2224 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2226 if (errno == ENODEV) {
2227 r = LIBUSB_ERROR_NO_DEVICE;
2228 } else if (errno == EINVAL) {
2229 usbi_warn(TRANSFER_CTX(transfer),
2230 "submiturb failed, transfer too large");
2231 r = LIBUSB_ERROR_INVALID_PARAM;
2232 } else if (errno == EMSGSIZE) {
2233 usbi_warn(TRANSFER_CTX(transfer),
2234 "submiturb failed, iso packet length too large");
2235 r = LIBUSB_ERROR_INVALID_PARAM;
2237 usbi_err(TRANSFER_CTX(transfer),
2238 "submiturb failed error %d errno=%d", r, errno);
2239 r = LIBUSB_ERROR_IO;
2242 /* if the first URB submission fails, we can simply free up and
2243 * return failure immediately. */
2245 usbi_dbg("first URB failed, easy peasy");
2246 free_iso_urbs(tpriv);
2250 /* if it's not the first URB that failed, the situation is a bit
2251 * tricky. we must discard all previous URBs. there are
2253 * - discarding is asynchronous - discarded urbs will be reaped
2254 * later. the user must not have freed the transfer when the
2255 * discarded URBs are reaped, otherwise libusb will be using
2257 * - the earlier URBs may have completed successfully and we do
2258 * not want to throw away any data.
2259 * so, in this case we discard all the previous URBs BUT we report
2260 * that the transfer was submitted successfully. then later when
2261 * the final discard completes we can report error to the user.
2263 tpriv->reap_action = SUBMIT_FAILED;
2265 /* The URBs we haven't submitted yet we count as already
2267 tpriv->num_retired = num_urbs - i;
2268 discard_urbs(itransfer, 0, i);
2270 usbi_dbg("reporting successful submission but waiting for %d "
2271 "discards before reporting error", i);
2279 static int submit_control_transfer(struct usbi_transfer *itransfer)
2281 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2282 struct libusb_transfer *transfer =
2283 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2284 struct linux_device_handle_priv *dpriv =
2285 _device_handle_priv(transfer->dev_handle);
2286 struct usbfs_urb *urb;
2289 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2290 return LIBUSB_ERROR_INVALID_PARAM;
2292 urb = calloc(1, sizeof(struct usbfs_urb));
2294 return LIBUSB_ERROR_NO_MEM;
2296 tpriv->num_urbs = 1;
2297 tpriv->reap_action = NORMAL;
2299 urb->usercontext = itransfer;
2300 urb->type = USBFS_URB_TYPE_CONTROL;
2301 urb->endpoint = transfer->endpoint;
2302 urb->buffer = transfer->buffer;
2303 urb->buffer_length = transfer->length;
2305 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2309 if (errno == ENODEV)
2310 return LIBUSB_ERROR_NO_DEVICE;
2312 usbi_err(TRANSFER_CTX(transfer),
2313 "submiturb failed error %d errno=%d", r, errno);
2314 return LIBUSB_ERROR_IO;
2319 static int op_submit_transfer(struct usbi_transfer *itransfer)
2321 struct libusb_transfer *transfer =
2322 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2324 switch (transfer->type) {
2325 case LIBUSB_TRANSFER_TYPE_CONTROL:
2326 return submit_control_transfer(itransfer);
2327 case LIBUSB_TRANSFER_TYPE_BULK:
2328 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2329 return submit_bulk_transfer(itransfer);
2330 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2331 return submit_bulk_transfer(itransfer);
2332 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2333 return submit_iso_transfer(itransfer);
2335 usbi_err(TRANSFER_CTX(transfer),
2336 "unknown endpoint type %d", transfer->type);
2337 return LIBUSB_ERROR_INVALID_PARAM;
2341 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2343 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2344 struct libusb_transfer *transfer =
2345 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2349 return LIBUSB_ERROR_NOT_FOUND;
2351 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2355 switch (transfer->type) {
2356 case LIBUSB_TRANSFER_TYPE_BULK:
2357 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2358 if (tpriv->reap_action == ERROR)
2360 /* else, fall through */
2362 tpriv->reap_action = CANCELLED;
2368 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2370 struct libusb_transfer *transfer =
2371 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2372 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2374 switch (transfer->type) {
2375 case LIBUSB_TRANSFER_TYPE_CONTROL:
2376 case LIBUSB_TRANSFER_TYPE_BULK:
2377 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2378 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2384 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2385 if (tpriv->iso_urbs) {
2386 free_iso_urbs(tpriv);
2387 tpriv->iso_urbs = NULL;
2391 usbi_err(TRANSFER_CTX(transfer),
2392 "unknown endpoint type %d", transfer->type);
2396 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2397 struct usbfs_urb *urb)
2399 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2400 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2401 int urb_idx = urb - tpriv->urbs;
2403 usbi_mutex_lock(&itransfer->lock);
2404 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2405 urb_idx + 1, tpriv->num_urbs);
2407 tpriv->num_retired++;
2409 if (tpriv->reap_action != NORMAL) {
2410 /* cancelled, submit_fail, or completed early */
2411 usbi_dbg("abnormal reap: urb status %d", urb->status);
2413 /* even though we're in the process of cancelling, it's possible that
2414 * we may receive some data in these URBs that we don't want to lose.
2416 * 1. while the kernel is cancelling all the packets that make up an
2417 * URB, a few of them might complete. so we get back a successful
2418 * cancellation *and* some data.
2419 * 2. we receive a short URB which marks the early completion condition,
2420 * so we start cancelling the remaining URBs. however, we're too
2421 * slow and another URB completes (or at least completes partially).
2422 * (this can't happen since we always use BULK_CONTINUATION.)
2424 * When this happens, our objectives are not to lose any "surplus" data,
2425 * and also to stick it at the end of the previously-received data
2426 * (closing any holes), so that libusb reports the total amount of
2427 * transferred data and presents it in a contiguous chunk.
2429 if (urb->actual_length > 0) {
2430 unsigned char *target = transfer->buffer + itransfer->transferred;
2431 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2432 if (urb->buffer != target) {
2433 usbi_dbg("moving surplus data from offset %d to offset %d",
2434 (unsigned char *) urb->buffer - transfer->buffer,
2435 target - transfer->buffer);
2436 memmove(target, urb->buffer, urb->actual_length);
2438 itransfer->transferred += urb->actual_length;
2441 if (tpriv->num_retired == tpriv->num_urbs) {
2442 usbi_dbg("abnormal reap: last URB handled, reporting");
2443 if (tpriv->reap_action != COMPLETED_EARLY &&
2444 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2445 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2451 itransfer->transferred += urb->actual_length;
2453 /* Many of these errors can occur on *any* urb of a multi-urb
2454 * transfer. When they do, we tear down the rest of the transfer.
2456 switch (urb->status) {
2459 case -EREMOTEIO: /* short transfer */
2461 case -ENOENT: /* cancelled */
2466 usbi_dbg("device removed");
2467 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2468 goto cancel_remaining;
2470 usbi_dbg("detected endpoint stall");
2471 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2472 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2473 goto cancel_remaining;
2475 /* overflow can only ever occur in the last urb */
2476 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2477 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2478 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2485 usbi_dbg("low level error %d", urb->status);
2486 tpriv->reap_action = ERROR;
2487 goto cancel_remaining;
2489 usbi_warn(ITRANSFER_CTX(itransfer),
2490 "unrecognised urb status %d", urb->status);
2491 tpriv->reap_action = ERROR;
2492 goto cancel_remaining;
2495 /* if we're the last urb or we got less data than requested then we're
2497 if (urb_idx == tpriv->num_urbs - 1) {
2498 usbi_dbg("last URB in transfer --> complete!");
2500 } else if (urb->actual_length < urb->buffer_length) {
2501 usbi_dbg("short transfer %d/%d --> complete!",
2502 urb->actual_length, urb->buffer_length);
2503 if (tpriv->reap_action == NORMAL)
2504 tpriv->reap_action = COMPLETED_EARLY;
2509 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2510 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2512 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2515 /* cancel remaining urbs and wait for their completion before
2516 * reporting results */
2517 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2520 usbi_mutex_unlock(&itransfer->lock);
2526 usbi_mutex_unlock(&itransfer->lock);
2527 return CANCELLED == tpriv->reap_action ?
2528 usbi_handle_transfer_cancellation(itransfer) :
2529 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2532 static int handle_iso_completion(struct usbi_transfer *itransfer,
2533 struct usbfs_urb *urb)
2535 struct libusb_transfer *transfer =
2536 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2537 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2538 int num_urbs = tpriv->num_urbs;
2541 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2543 usbi_mutex_lock(&itransfer->lock);
2544 for (i = 0; i < num_urbs; i++) {
2545 if (urb == tpriv->iso_urbs[i]) {
2551 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2552 usbi_mutex_unlock(&itransfer->lock);
2553 return LIBUSB_ERROR_NOT_FOUND;
2556 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2559 /* copy isochronous results back in */
2561 for (i = 0; i < urb->number_of_packets; i++) {
2562 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2563 struct libusb_iso_packet_descriptor *lib_desc =
2564 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2565 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2566 switch (urb_desc->status) {
2569 case -ENOENT: /* cancelled */
2574 usbi_dbg("device removed");
2575 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2578 usbi_dbg("detected endpoint stall");
2579 lib_desc->status = LIBUSB_TRANSFER_STALL;
2582 usbi_dbg("overflow error");
2583 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2591 usbi_dbg("low-level USB error %d", urb_desc->status);
2592 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2595 usbi_warn(TRANSFER_CTX(transfer),
2596 "unrecognised urb status %d", urb_desc->status);
2597 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2600 lib_desc->actual_length = urb_desc->actual_length;
2603 tpriv->num_retired++;
2605 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2606 usbi_dbg("CANCEL: urb status %d", urb->status);
2608 if (tpriv->num_retired == num_urbs) {
2609 usbi_dbg("CANCEL: last URB handled, reporting");
2610 free_iso_urbs(tpriv);
2611 if (tpriv->reap_action == CANCELLED) {
2612 usbi_mutex_unlock(&itransfer->lock);
2613 return usbi_handle_transfer_cancellation(itransfer);
2615 usbi_mutex_unlock(&itransfer->lock);
2616 return usbi_handle_transfer_completion(itransfer,
2617 LIBUSB_TRANSFER_ERROR);
2623 switch (urb->status) {
2626 case -ENOENT: /* cancelled */
2630 usbi_dbg("device removed");
2631 status = LIBUSB_TRANSFER_NO_DEVICE;
2634 usbi_warn(TRANSFER_CTX(transfer),
2635 "unrecognised urb status %d", urb->status);
2636 status = LIBUSB_TRANSFER_ERROR;
2640 /* if we're the last urb then we're done */
2641 if (urb_idx == num_urbs) {
2642 usbi_dbg("last URB in transfer --> complete!");
2643 free_iso_urbs(tpriv);
2644 usbi_mutex_unlock(&itransfer->lock);
2645 return usbi_handle_transfer_completion(itransfer, status);
2649 usbi_mutex_unlock(&itransfer->lock);
2653 static int handle_control_completion(struct usbi_transfer *itransfer,
2654 struct usbfs_urb *urb)
2656 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2659 usbi_mutex_lock(&itransfer->lock);
2660 usbi_dbg("handling completion status %d", urb->status);
2662 itransfer->transferred += urb->actual_length;
2664 if (tpriv->reap_action == CANCELLED) {
2665 if (urb->status != 0 && urb->status != -ENOENT)
2666 usbi_warn(ITRANSFER_CTX(itransfer),
2667 "cancel: unrecognised urb status %d", urb->status);
2670 usbi_mutex_unlock(&itransfer->lock);
2671 return usbi_handle_transfer_cancellation(itransfer);
2674 switch (urb->status) {
2676 status = LIBUSB_TRANSFER_COMPLETED;
2678 case -ENOENT: /* cancelled */
2679 status = LIBUSB_TRANSFER_CANCELLED;
2683 usbi_dbg("device removed");
2684 status = LIBUSB_TRANSFER_NO_DEVICE;
2687 usbi_dbg("unsupported control request");
2688 status = LIBUSB_TRANSFER_STALL;
2691 usbi_dbg("control overflow error");
2692 status = LIBUSB_TRANSFER_OVERFLOW;
2699 usbi_dbg("low-level bus error occurred");
2700 status = LIBUSB_TRANSFER_ERROR;
2703 usbi_warn(ITRANSFER_CTX(itransfer),
2704 "unrecognised urb status %d", urb->status);
2705 status = LIBUSB_TRANSFER_ERROR;
2711 usbi_mutex_unlock(&itransfer->lock);
2712 return usbi_handle_transfer_completion(itransfer, status);
2715 static int reap_for_handle(struct libusb_device_handle *handle)
2717 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2719 struct usbfs_urb *urb;
2720 struct usbi_transfer *itransfer;
2721 struct libusb_transfer *transfer;
2723 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2724 if (r == -1 && errno == EAGAIN)
2727 if (errno == ENODEV)
2728 return LIBUSB_ERROR_NO_DEVICE;
2730 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2732 return LIBUSB_ERROR_IO;
2735 itransfer = urb->usercontext;
2736 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2738 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2739 urb->actual_length);
2741 switch (transfer->type) {
2742 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2743 return handle_iso_completion(itransfer, urb);
2744 case LIBUSB_TRANSFER_TYPE_BULK:
2745 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2746 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2747 return handle_bulk_completion(itransfer, urb);
2748 case LIBUSB_TRANSFER_TYPE_CONTROL:
2749 return handle_control_completion(itransfer, urb);
2751 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2753 return LIBUSB_ERROR_OTHER;
2757 static int op_handle_events(struct libusb_context *ctx,
2758 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2763 usbi_mutex_lock(&ctx->open_devs_lock);
2764 for (i = 0; i < nfds && num_ready > 0; i++) {
2765 struct pollfd *pollfd = &fds[i];
2766 struct libusb_device_handle *handle;
2767 struct linux_device_handle_priv *hpriv = NULL;
2769 if (!pollfd->revents)
2773 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2774 hpriv = _device_handle_priv(handle);
2775 if (hpriv->fd == pollfd->fd)
2779 if (!hpriv || hpriv->fd != pollfd->fd) {
2780 usbi_err(ctx, "cannot find handle for fd %d",
2785 if (pollfd->revents & POLLERR) {
2786 /* remove the fd from the pollfd set so that it doesn't continuously
2787 * trigger an event, and flag that it has been removed so op_close()
2788 * doesn't try to remove it a second time */
2789 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2790 hpriv->fd_removed = 1;
2792 /* device will still be marked as attached if hotplug monitor thread
2793 * hasn't processed remove event yet */
2794 usbi_mutex_static_lock(&linux_hotplug_lock);
2795 if (handle->dev->attached)
2796 linux_device_disconnected(handle->dev->bus_number,
2797 handle->dev->device_address);
2798 usbi_mutex_static_unlock(&linux_hotplug_lock);
2800 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2802 r = reap_for_handle(handle);
2806 usbi_handle_disconnect(handle);
2811 r = reap_for_handle(handle);
2813 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2821 usbi_mutex_unlock(&ctx->open_devs_lock);
2825 static int op_clock_gettime(int clk_id, struct timespec *tp)
2828 case USBI_CLOCK_MONOTONIC:
2829 return clock_gettime(monotonic_clkid, tp);
2830 case USBI_CLOCK_REALTIME:
2831 return clock_gettime(CLOCK_REALTIME, tp);
2833 return LIBUSB_ERROR_INVALID_PARAM;
2837 #ifdef USBI_TIMERFD_AVAILABLE
2838 static clockid_t op_get_timerfd_clockid(void)
2840 return monotonic_clkid;
2845 const struct usbi_os_backend usbi_backend = {
2846 .name = "Linux usbfs",
2847 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2850 .get_device_list = NULL,
2851 .hotplug_poll = op_hotplug_poll,
2852 .get_device_descriptor = op_get_device_descriptor,
2853 .get_active_config_descriptor = op_get_active_config_descriptor,
2854 .get_config_descriptor = op_get_config_descriptor,
2855 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2857 .wrap_sys_device = op_wrap_sys_device,
2860 .get_configuration = op_get_configuration,
2861 .set_configuration = op_set_configuration,
2862 .claim_interface = op_claim_interface,
2863 .release_interface = op_release_interface,
2865 .set_interface_altsetting = op_set_interface,
2866 .clear_halt = op_clear_halt,
2867 .reset_device = op_reset_device,
2869 .alloc_streams = op_alloc_streams,
2870 .free_streams = op_free_streams,
2872 .dev_mem_alloc = op_dev_mem_alloc,
2873 .dev_mem_free = op_dev_mem_free,
2875 .kernel_driver_active = op_kernel_driver_active,
2876 .detach_kernel_driver = op_detach_kernel_driver,
2877 .attach_kernel_driver = op_attach_kernel_driver,
2879 .destroy_device = op_destroy_device,
2881 .submit_transfer = op_submit_transfer,
2882 .cancel_transfer = op_cancel_transfer,
2883 .clear_transfer_priv = op_clear_transfer_priv,
2885 .handle_events = op_handle_events,
2887 .clock_gettime = op_clock_gettime,
2889 #ifdef USBI_TIMERFD_AVAILABLE
2890 .get_timerfd_clockid = op_get_timerfd_clockid,
2893 .device_priv_size = sizeof(struct linux_device_priv),
2894 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2895 .transfer_priv_size = sizeof(struct linux_transfer_priv),