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
36 #include <sys/ioctl.h>
39 #include <sys/types.h>
40 #include <sys/utsname.h>
44 #include "linux_usbfs.h"
47 * opening a usbfs node causes the device to be resumed, so we attempt to
48 * avoid this during enumeration.
50 * sysfs allows us to read the kernel's in-memory copies of device descriptors
51 * and so forth, avoiding the need to open the device:
52 * - The binary "descriptors" file contains all config descriptors since
53 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
54 * - The binary "descriptors" file was added in 2.6.23, commit
55 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
56 * active config descriptors
57 * - The "busnum" file was added in 2.6.22, commit
58 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
59 * - The "devnum" file has been present since pre-2.6.18
60 * - the "bConfigurationValue" file has been present since pre-2.6.18
62 * If we have bConfigurationValue, busnum, and devnum, then we can determine
63 * the active configuration without having to open the usbfs node in RDWR mode.
64 * The busnum file is important as that is the only way we can relate sysfs
65 * devices to usbfs nodes.
67 * If we also have all descriptors, we can obtain the device descriptor and
68 * configuration without touching usbfs at all.
71 /* endianness for multi-byte fields:
73 * Descriptors exposed by usbfs have the multi-byte fields in the device
74 * descriptor as host endian. Multi-byte fields in the other descriptors are
75 * bus-endian. The kernel documentation says otherwise, but it is wrong.
77 * In sysfs all descriptors are bus-endian.
80 #define USBDEV_PATH "/dev"
81 #define USB_DEVTMPFS_PATH "/dev/bus/usb"
83 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
84 static int usbdev_names = 0;
86 /* Linux has changed the maximum length of an individual isochronous packet
87 * over time. Initially this limit was 1,023 bytes, but Linux 2.6.18
88 * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
89 * 8,192 bytes to support higher bandwidth devices. Linux 3.10
90 * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
91 * value to 49,152 bytes to support super speed devices.
93 static unsigned int max_iso_packet_len = 0;
95 /* Linux 2.6.23 adds support for O_CLOEXEC when opening files, which marks the
96 * close-on-exec flag in the underlying file descriptor. */
97 static int supports_flag_cloexec = -1;
99 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
100 * allows us to mark URBs as being part of a specific logical transfer when
101 * we submit them to the kernel. then, on any error except a cancellation, all
102 * URBs within that transfer will be cancelled and no more URBs will be
103 * accepted for the transfer, meaning that no more data can creep in.
105 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
106 * (in either direction) except the first.
107 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
108 * last; it means that the kernel should treat a short reply as an error.
109 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
110 * transfers can't be short unless there's already some sort of error), and
111 * setting this flag is disallowed (a kernel with USB debugging enabled will
114 static int supports_flag_bulk_continuation = -1;
116 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
117 * allows us to mark URBs that should be followed by a zero length data
118 * packet, which can be required by device- or class-specific protocols.
120 static int supports_flag_zero_packet = -1;
122 /* clock ID for monotonic clock, as not all clock sources are available on all
123 * systems. appropriate choice made at initialization time. */
124 static clockid_t monotonic_clkid = -1;
126 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
127 * to sysfs, so we can relate devices. This also implies that we can read
128 * the active configuration through bConfigurationValue */
129 static int sysfs_can_relate_devices = -1;
131 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
132 * config descriptors (rather then just the active config) to the sysfs
133 * descriptors file, so from then on we can use them. */
134 static int sysfs_has_descriptors = -1;
136 /* how many times have we initted (and not exited) ? */
137 static int init_count = 0;
139 /* Serialize hotplug start/stop */
140 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
141 /* Serialize scan-devices, event-thread, and poll */
142 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
144 static int linux_scan_devices(struct libusb_context *ctx);
145 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
147 #if !defined(HAVE_LIBUDEV)
148 static int linux_default_scan_devices(struct libusb_context *ctx);
151 struct kernel_version {
157 struct linux_device_priv {
159 unsigned char *descriptors;
161 int active_config; /* cache val for !sysfs_can_relate_devices */
164 struct linux_device_handle_priv {
173 /* submission failed after the first URB, so await cancellation/completion
174 * of all the others */
177 /* cancelled by user or timeout */
180 /* completed multi-URB transfer in non-final URB */
183 /* one or more urbs encountered a low-level error */
187 struct linux_transfer_priv {
189 struct usbfs_urb *urbs;
190 struct usbfs_urb **iso_urbs;
193 enum reap_action reap_action;
196 enum libusb_transfer_status reap_status;
198 /* next iso packet in user-supplied transfer to be populated */
199 int iso_packet_offset;
202 static int __open(const char *path, int flags)
204 #if defined(O_CLOEXEC)
205 if (supports_flag_cloexec)
206 return open(path, flags | O_CLOEXEC);
209 return open(path, flags);
212 static int get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
214 struct libusb_context *ctx = DEVICE_CTX(dev);
219 sprintf(path, USBDEV_PATH "/usbdev%u.%u",
220 dev->bus_number, dev->device_address);
222 sprintf(path, USB_DEVTMPFS_PATH "/%03u/%03u",
223 dev->bus_number, dev->device_address);
225 fd = __open(path, mode);
227 return fd; /* Success */
229 if (errno == ENOENT) {
230 const long delay_ms = 10L;
231 const struct timespec delay_ts = { 0L, delay_ms * 1000L * 1000L };
234 usbi_err(ctx, "File doesn't exist, wait %ld ms and try again", delay_ms);
236 /* Wait 10ms for USB device path creation.*/
237 nanosleep(&delay_ts, NULL);
239 fd = __open(path, mode);
241 return fd; /* Success */
245 usbi_err(ctx, "libusb couldn't open USB device %s, errno=%d", path, errno);
246 if (errno == EACCES && mode == O_RDWR)
247 usbi_err(ctx, "libusb requires write access to USB device nodes");
251 return LIBUSB_ERROR_ACCESS;
253 return LIBUSB_ERROR_NO_DEVICE;
254 return LIBUSB_ERROR_IO;
257 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
259 return (struct linux_device_priv *)dev->os_priv;
262 static struct linux_device_handle_priv *_device_handle_priv(
263 struct libusb_device_handle *handle)
265 return (struct linux_device_handle_priv *)handle->os_priv;
268 /* check dirent for a /dev/usbdev%d.%d name
269 * optionally return bus/device on success */
270 static int _is_usbdev_entry(const char *name, uint8_t *bus_p, uint8_t *dev_p)
274 if (sscanf(name, "usbdev%d.%d", &busnum, &devnum) != 2)
276 if (busnum < 0 || busnum > UINT8_MAX || devnum < 0 || devnum > UINT8_MAX) {
277 usbi_dbg("invalid usbdev format '%s'", name);
281 usbi_dbg("found: %s", name);
283 *bus_p = (uint8_t)busnum;
285 *dev_p = (uint8_t)devnum;
289 static int check_usb_vfs(const char *dirname)
292 struct dirent *entry;
295 dir = opendir(dirname);
299 while ((entry = readdir(dir))) {
300 if (entry->d_name[0] == '.')
303 /* We assume if we find any files that it must be the right place */
312 static const char *find_usbfs_path(void)
314 const char *path = "/dev/bus/usb";
315 const char *ret = NULL;
317 if (check_usb_vfs(path)) {
320 path = "/proc/bus/usb";
321 if (check_usb_vfs(path))
325 /* look for /dev/usbdev*.* if the normal places fail */
327 struct dirent *entry;
333 while ((entry = readdir(dir))) {
334 if (_is_usbdev_entry(entry->d_name, NULL, NULL)) {
335 /* found one; that's enough */
345 /* On udev based systems without any usb-devices /dev/bus/usb will not
346 * exist. So if we've not found anything and we're using udev for hotplug
347 * simply assume /dev/bus/usb rather then making libusb_init fail.
348 * Make the same assumption for Android where SELinux policies might block us
349 * from reading /dev on newer devices. */
350 #if defined(HAVE_LIBUDEV) || defined(__ANDROID__)
352 ret = "/dev/bus/usb";
356 usbi_dbg("found usbfs at %s", ret);
361 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
362 * seem to lack it). fall back to REALTIME if we have to. */
363 static clockid_t find_monotonic_clock(void)
365 #ifdef CLOCK_MONOTONIC
369 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
370 * because it's not available through timerfd */
371 r = clock_gettime(CLOCK_MONOTONIC, &ts);
373 return CLOCK_MONOTONIC;
374 usbi_dbg("monotonic clock doesn't work, errno=%d", errno);
377 return CLOCK_REALTIME;
380 static int get_kernel_version(struct libusb_context *ctx,
381 struct kernel_version *ver)
386 if (uname(&uts) < 0) {
387 usbi_err(ctx, "uname failed, errno=%d", errno);
391 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
393 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
400 usbi_dbg("reported kernel version is %s", uts.release);
405 static int kernel_version_ge(const struct kernel_version *ver,
406 int major, int minor, int sublevel)
408 if (ver->major > major)
410 else if (ver->major < major)
413 /* kmajor == major */
414 if (ver->minor > minor)
416 else if (ver->minor < minor)
419 /* kminor == minor */
420 if (ver->sublevel == -1)
421 return sublevel == 0;
423 return ver->sublevel >= sublevel;
426 static int op_init(struct libusb_context *ctx)
428 struct kernel_version kversion;
432 if (!find_usbfs_path()) {
433 usbi_err(ctx, "could not find usbfs");
434 return LIBUSB_ERROR_OTHER;
437 if (monotonic_clkid == -1)
438 monotonic_clkid = find_monotonic_clock();
440 if (get_kernel_version(ctx, &kversion) < 0)
441 return LIBUSB_ERROR_OTHER;
443 if (supports_flag_cloexec == -1) {
444 /* O_CLOEXEC flag available from Linux 2.6.23 */
445 supports_flag_cloexec = kernel_version_ge(&kversion, 2, 6, 23);
448 if (supports_flag_bulk_continuation == -1) {
449 /* bulk continuation URB flag available from Linux 2.6.32 */
450 supports_flag_bulk_continuation = kernel_version_ge(&kversion,2,6,32);
453 if (supports_flag_bulk_continuation)
454 usbi_dbg("bulk continuation flag supported");
456 if (supports_flag_zero_packet == -1) {
457 /* zero length packet URB flag fixed since Linux 2.6.31 */
458 supports_flag_zero_packet = kernel_version_ge(&kversion, 2, 6, 31);
461 if (supports_flag_zero_packet)
462 usbi_dbg("zero length packet flag supported");
464 if (!max_iso_packet_len) {
465 if (kernel_version_ge(&kversion, 3, 10, 0))
466 max_iso_packet_len = 49152;
467 else if (kernel_version_ge(&kversion, 2, 6, 18))
468 max_iso_packet_len = 8192;
470 max_iso_packet_len = 1023;
473 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
475 if (sysfs_has_descriptors == -1) {
476 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
477 sysfs_has_descriptors = kernel_version_ge(&kversion, 2, 6, 26);
480 if (sysfs_can_relate_devices == -1) {
481 /* sysfs has busnum since Linux 2.6.22 */
482 sysfs_can_relate_devices = kernel_version_ge(&kversion, 2, 6, 22);
485 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
486 r = stat(SYSFS_DEVICE_PATH, &statbuf);
487 if (r < 0 || !S_ISDIR(statbuf.st_mode)) {
488 usbi_warn(ctx, "sysfs not mounted");
489 sysfs_can_relate_devices = 0;
490 sysfs_has_descriptors = 0;
494 if (sysfs_can_relate_devices)
495 usbi_dbg("sysfs can relate devices");
497 if (sysfs_has_descriptors)
498 usbi_dbg("sysfs has complete descriptors");
500 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
502 if (init_count == 0) {
503 /* start up hotplug event handler */
504 r = linux_start_event_monitor();
506 if (r == LIBUSB_SUCCESS) {
507 r = linux_scan_devices(ctx);
508 if (r == LIBUSB_SUCCESS)
510 else if (init_count == 0)
511 linux_stop_event_monitor();
513 usbi_err(ctx, "error starting hotplug event monitor");
515 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
520 static void op_exit(struct libusb_context *ctx)
523 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
524 assert(init_count != 0);
526 /* tear down event handler */
527 linux_stop_event_monitor();
529 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
532 static int linux_scan_devices(struct libusb_context *ctx)
536 usbi_mutex_static_lock(&linux_hotplug_lock);
538 #if defined(HAVE_LIBUDEV)
539 ret = linux_udev_scan_devices(ctx);
541 ret = linux_default_scan_devices(ctx);
544 usbi_mutex_static_unlock(&linux_hotplug_lock);
549 static void op_hotplug_poll(void)
551 linux_hotplug_poll();
554 static int open_sysfs_attr(struct libusb_context *ctx,
555 const char *sysfs_dir, const char *attr)
560 snprintf(filename, sizeof(filename), SYSFS_DEVICE_PATH "/%s/%s", sysfs_dir, attr);
561 fd = __open(filename, O_RDONLY);
563 if (errno == ENOENT) {
564 /* File doesn't exist. Assume the device has been
565 disconnected (see trac ticket #70). */
566 return LIBUSB_ERROR_NO_DEVICE;
568 usbi_err(ctx, "open %s failed, errno=%d", filename, errno);
569 return LIBUSB_ERROR_IO;
575 /* Note only suitable for attributes which always read >= 0, < 0 is error */
576 static int read_sysfs_attr(struct libusb_context *ctx,
577 const char *sysfs_dir, const char *attr, int max_value, int *value_p)
579 char buf[20], *endptr;
584 fd = open_sysfs_attr(ctx, sysfs_dir, attr);
588 r = read(fd, buf, sizeof(buf));
593 return LIBUSB_ERROR_NO_DEVICE;
594 usbi_err(ctx, "attribute %s read failed, errno=%zd", attr, r);
595 return LIBUSB_ERROR_IO;
600 /* Certain attributes (e.g. bConfigurationValue) are not
601 * populated if the device is not configured. */
606 /* The kernel does *not* NULL-terminate the string, but every attribute
607 * should be terminated with a newline character. */
608 if (!isdigit(buf[0])) {
609 usbi_err(ctx, "attribute %s doesn't have numeric value?", attr);
610 return LIBUSB_ERROR_IO;
611 } else if (buf[r - 1] != '\n') {
612 usbi_err(ctx, "attribute %s doesn't end with newline?", attr);
613 return LIBUSB_ERROR_IO;
618 value = strtol(buf, &endptr, 10);
619 if (value < 0 || value > (long)max_value || errno) {
620 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
621 return LIBUSB_ERROR_INVALID_PARAM;
622 } else if (*endptr != '\0') {
623 /* Consider the value to be valid if the remainder is a '.'
624 * character followed by numbers. This occurs, for example,
625 * when reading the "speed" attribute for a low-speed device
627 if (*endptr == '.' && isdigit(*(endptr + 1))) {
629 while (isdigit(*endptr))
632 if (*endptr != '\0') {
633 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
634 return LIBUSB_ERROR_INVALID_PARAM;
638 *value_p = (int)value;
642 static int op_get_device_descriptor(struct libusb_device *dev,
643 unsigned char *buffer, int *host_endian)
645 struct linux_device_priv *priv = _device_priv(dev);
647 *host_endian = (priv->sysfs_dir && sysfs_has_descriptors) ? 0 : 1;
648 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
653 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
655 uint8_t busnum, devaddr;
658 ret = linux_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname, -1);
659 if (ret != LIBUSB_SUCCESS)
662 return linux_enumerate_device(ctx, busnum, devaddr, devname);
665 /* read the bConfigurationValue for a device */
666 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
668 struct linux_device_priv *priv = _device_priv(dev);
671 ret = read_sysfs_attr(DEVICE_CTX(dev), priv->sysfs_dir, "bConfigurationValue",
677 usbi_dbg("device unconfigured");
682 int linux_get_device_address(struct libusb_context *ctx, int detached,
683 uint8_t *busnum, uint8_t *devaddr, const char *dev_node,
684 const char *sys_name, int fd)
689 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
690 /* can't use sysfs to read the bus and device number if the
691 * device has been detached */
692 if (!sysfs_can_relate_devices || detached || !sys_name) {
693 if (!dev_node && fd >= 0) {
694 char *fd_path = alloca(PATH_MAX);
697 /* try to retrieve the device node from fd */
698 sprintf(proc_path, "/proc/self/fd/%d", fd);
699 r = readlink(proc_path, fd_path, PATH_MAX - 1);
707 return LIBUSB_ERROR_OTHER;
709 /* will this work with all supported kernel versions? */
710 if (!strncmp(dev_node, "/dev/bus/usb", 12))
711 sscanf(dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
712 else if (!strncmp(dev_node, "/proc/bus/usb", 13))
713 sscanf(dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
715 return LIBUSB_ERROR_OTHER;
717 return LIBUSB_SUCCESS;
720 usbi_dbg("scan %s", sys_name);
722 r = read_sysfs_attr(ctx, sys_name, "busnum", UINT8_MAX, &sysfs_val);
725 *busnum = (uint8_t)sysfs_val;
727 r = read_sysfs_attr(ctx, sys_name, "devnum", UINT8_MAX, &sysfs_val);
730 *devaddr = (uint8_t)sysfs_val;
732 usbi_dbg("bus=%u dev=%u", *busnum, *devaddr);
734 return LIBUSB_SUCCESS;
737 /* Return offset of the next descriptor with the given type */
738 static int seek_to_next_descriptor(struct libusb_context *ctx,
739 uint8_t descriptor_type, unsigned char *buffer, int size)
741 struct usb_descriptor_header header;
744 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
746 return LIBUSB_ERROR_NOT_FOUND;
749 usbi_err(ctx, "short descriptor read %d/2", size);
750 return LIBUSB_ERROR_IO;
752 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
754 if (i && header.bDescriptorType == descriptor_type)
757 usbi_err(ctx, "bLength overflow by %d bytes", -size);
758 return LIBUSB_ERROR_IO;
761 /* Return offset to next config */
762 static int seek_to_next_config(struct libusb_device *dev,
763 unsigned char *buffer, int size)
765 struct libusb_context *ctx = DEVICE_CTX(dev);
766 struct linux_device_priv *priv = _device_priv(dev);
767 struct libusb_config_descriptor config;
770 return LIBUSB_ERROR_NOT_FOUND;
772 if (size < LIBUSB_DT_CONFIG_SIZE) {
773 usbi_err(ctx, "short descriptor read %d/%d",
774 size, LIBUSB_DT_CONFIG_SIZE);
775 return LIBUSB_ERROR_IO;
778 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
779 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
780 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
781 config.bDescriptorType);
782 return LIBUSB_ERROR_IO;
786 * In usbfs the config descriptors are config.wTotalLength bytes apart,
787 * with any short reads from the device appearing as holes in the file.
789 * In sysfs wTotalLength is ignored, instead the kernel returns a
790 * config descriptor with verified bLength fields, with descriptors
791 * with an invalid bLength removed.
793 if (priv->sysfs_dir && sysfs_has_descriptors) {
794 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG, buffer, size);
796 if (next == LIBUSB_ERROR_NOT_FOUND)
801 if (next != config.wTotalLength)
802 usbi_warn(ctx, "config length mismatch wTotalLength %u real %d",
803 config.wTotalLength, next);
806 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
807 usbi_err(ctx, "invalid wTotalLength %u", config.wTotalLength);
808 return LIBUSB_ERROR_IO;
809 } else if (config.wTotalLength > size) {
810 usbi_warn(ctx, "short descriptor read %d/%u",
811 size, config.wTotalLength);
814 return config.wTotalLength;
819 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
820 uint8_t value, unsigned char **buffer, int *host_endian)
822 struct linux_device_priv *priv = _device_priv(dev);
823 unsigned char *descriptors = priv->descriptors;
824 int size = priv->descriptors_len;
825 struct libusb_config_descriptor *config;
828 /* Unlike the device desc. config descs. are always in raw format */
831 /* Skip device header */
832 descriptors += DEVICE_DESC_LENGTH;
833 size -= DEVICE_DESC_LENGTH;
835 /* Seek till the config is found, or till "EOF" */
837 int next = seek_to_next_config(dev, descriptors, size);
841 config = (struct libusb_config_descriptor *)descriptors;
842 if (config->bConfigurationValue == value) {
843 *buffer = descriptors;
851 static int op_get_active_config_descriptor(struct libusb_device *dev,
852 unsigned char *buffer, size_t len, int *host_endian)
854 struct linux_device_priv *priv = _device_priv(dev);
856 unsigned char *config_desc;
858 if (priv->sysfs_dir && sysfs_can_relate_devices) {
859 r = sysfs_get_active_config(dev, &config);
863 /* Use cached bConfigurationValue */
864 config = priv->active_config;
867 return LIBUSB_ERROR_NOT_FOUND;
869 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
874 len = MIN(len, (size_t)r);
875 memcpy(buffer, config_desc, len);
879 static int op_get_config_descriptor(struct libusb_device *dev,
880 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
882 struct linux_device_priv *priv = _device_priv(dev);
883 unsigned char *descriptors = priv->descriptors;
884 int i, r, size = priv->descriptors_len;
886 /* Unlike the device desc. config descs. are always in raw format */
889 /* Skip device header */
890 descriptors += DEVICE_DESC_LENGTH;
891 size -= DEVICE_DESC_LENGTH;
893 /* Seek till the config is found, or till "EOF" */
895 r = seek_to_next_config(dev, descriptors, size);
898 if (i == config_index)
904 len = MIN(len, (size_t)r);
905 memcpy(buffer, descriptors, len);
909 /* send a control message to retrieve active configuration */
910 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
912 struct linux_device_priv *priv = _device_priv(dev);
913 unsigned char active_config = 0;
916 struct usbfs_ctrltransfer ctrl = {
917 .bmRequestType = LIBUSB_ENDPOINT_IN,
918 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
923 .data = &active_config
926 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
929 return LIBUSB_ERROR_NO_DEVICE;
931 /* we hit this error path frequently with buggy devices :( */
932 usbi_warn(DEVICE_CTX(dev), "get configuration failed, errno=%d", errno);
933 priv->active_config = -1;
935 if (active_config > 0) {
936 priv->active_config = active_config;
938 /* some buggy devices have a configuration 0, but we're
939 * reaching into the corner of a corner case here, so let's
940 * not support buggy devices in these circumstances.
941 * stick to the specs: a configuration value of 0 means
943 usbi_warn(DEVICE_CTX(dev), "active cfg 0? assuming unconfigured device");
944 priv->active_config = -1;
948 return LIBUSB_SUCCESS;
951 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
952 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
954 struct linux_device_priv *priv = _device_priv(dev);
955 struct libusb_context *ctx = DEVICE_CTX(dev);
956 int descriptors_size = 0;
960 dev->bus_number = busnum;
961 dev->device_address = devaddr;
964 priv->sysfs_dir = strdup(sysfs_dir);
965 if (!priv->sysfs_dir)
966 return LIBUSB_ERROR_NO_MEM;
968 /* Note speed can contain 1.5, in this case read_sysfs_attr()
969 will stop parsing at the '.' and return 1 */
970 if (read_sysfs_attr(ctx, sysfs_dir, "speed", INT_MAX, &speed) == 0) {
972 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
973 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
974 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
975 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
976 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
978 usbi_warn(ctx, "unknown device speed: %d Mbps", speed);
983 /* cache descriptors in memory */
984 if (sysfs_dir && sysfs_has_descriptors) {
985 fd = open_sysfs_attr(ctx, sysfs_dir, "descriptors");
986 } else if (wrapped_fd < 0) {
987 fd = get_usbfs_fd(dev, O_RDONLY, 0);
990 r = lseek(fd, 0, SEEK_SET);
992 usbi_err(ctx, "lseek failed, errno=%d", errno);
993 return LIBUSB_ERROR_IO;
1000 descriptors_size += 256;
1001 priv->descriptors = usbi_reallocf(priv->descriptors, descriptors_size);
1002 if (!priv->descriptors) {
1003 if (fd != wrapped_fd)
1005 return LIBUSB_ERROR_NO_MEM;
1007 /* usbfs has holes in the file */
1008 if (!(sysfs_dir && sysfs_has_descriptors)) {
1009 memset(priv->descriptors + priv->descriptors_len,
1010 0, descriptors_size - priv->descriptors_len);
1012 r = read(fd, priv->descriptors + priv->descriptors_len,
1013 descriptors_size - priv->descriptors_len);
1015 usbi_err(ctx, "read descriptor failed, errno=%d", errno);
1016 if (fd != wrapped_fd)
1018 return LIBUSB_ERROR_IO;
1020 priv->descriptors_len += r;
1021 } while (priv->descriptors_len == descriptors_size);
1023 if (fd != wrapped_fd)
1026 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1027 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
1028 return LIBUSB_ERROR_IO;
1031 if (sysfs_dir && sysfs_can_relate_devices)
1032 return LIBUSB_SUCCESS;
1034 /* cache active config */
1036 fd = get_usbfs_fd(dev, O_RDWR, 1);
1040 /* cannot send a control message to determine the active
1041 * config. just assume the first one is active. */
1042 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1043 "active configuration descriptor");
1044 if (priv->descriptors_len >= (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1045 struct libusb_config_descriptor config;
1047 usbi_parse_descriptor(priv->descriptors + DEVICE_DESC_LENGTH,
1048 "bbwbbbbb", &config, 0);
1049 priv->active_config = config.bConfigurationValue;
1051 priv->active_config = -1; /* No config dt */
1054 return LIBUSB_SUCCESS;
1057 r = usbfs_get_active_config(dev, fd);
1058 if (fd != wrapped_fd)
1064 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1066 struct libusb_context *ctx = DEVICE_CTX(dev);
1067 struct libusb_device *it;
1068 char *parent_sysfs_dir, *tmp;
1069 int ret, add_parent = 1;
1071 /* XXX -- can we figure out the topology when using usbfs? */
1072 if (!sysfs_dir || !strncmp(sysfs_dir, "usb", 3)) {
1073 /* either using usbfs or finding the parent of a root hub */
1074 return LIBUSB_SUCCESS;
1077 parent_sysfs_dir = strdup(sysfs_dir);
1078 if (!parent_sysfs_dir)
1079 return LIBUSB_ERROR_NO_MEM;
1081 if ((tmp = strrchr(parent_sysfs_dir, '.')) ||
1082 (tmp = strrchr(parent_sysfs_dir, '-'))) {
1083 dev->port_number = atoi(tmp + 1);
1086 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1088 free(parent_sysfs_dir);
1089 return LIBUSB_SUCCESS;
1092 /* is the parent a root hub? */
1093 if (!strchr(parent_sysfs_dir, '-')) {
1094 tmp = parent_sysfs_dir;
1095 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
1098 return LIBUSB_ERROR_NO_MEM;
1102 /* find the parent in the context */
1103 usbi_mutex_lock(&ctx->usb_devs_lock);
1104 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1105 struct linux_device_priv *priv = _device_priv(it);
1107 if (priv->sysfs_dir) {
1108 if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
1109 dev->parent_dev = libusb_ref_device(it);
1114 usbi_mutex_unlock(&ctx->usb_devs_lock);
1116 if (!dev->parent_dev && add_parent) {
1117 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1119 sysfs_scan_device(ctx, parent_sysfs_dir);
1124 usbi_dbg("dev %p (%s) has parent %p (%s) port %u", dev, sysfs_dir,
1125 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1127 free(parent_sysfs_dir);
1129 return LIBUSB_SUCCESS;
1132 int linux_enumerate_device(struct libusb_context *ctx,
1133 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1135 unsigned long session_id;
1136 struct libusb_device *dev;
1139 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1140 * will be reused. instead we should add a simple sysfs attribute with
1142 session_id = busnum << 8 | devaddr;
1143 usbi_dbg("busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1145 dev = usbi_get_device_by_session_id(ctx, session_id);
1147 /* device already exists in the context */
1148 usbi_dbg("session_id %lu already exists", session_id);
1149 libusb_unref_device(dev);
1150 return LIBUSB_SUCCESS;
1153 usbi_dbg("allocating new device for %u/%u (session %lu)",
1154 busnum, devaddr, session_id);
1155 dev = usbi_alloc_device(ctx, session_id);
1157 return LIBUSB_ERROR_NO_MEM;
1159 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1162 r = usbi_sanitize_device(dev);
1166 r = linux_get_parent_info(dev, sysfs_dir);
1171 libusb_unref_device(dev);
1173 usbi_connect_device(dev);
1178 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1180 struct libusb_context *ctx;
1182 usbi_mutex_static_lock(&active_contexts_lock);
1183 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1184 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1186 usbi_mutex_static_unlock(&active_contexts_lock);
1189 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1191 struct libusb_context *ctx;
1192 struct libusb_device *dev;
1193 unsigned long session_id = busnum << 8 | devaddr;
1195 usbi_mutex_static_lock(&active_contexts_lock);
1196 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1197 dev = usbi_get_device_by_session_id (ctx, session_id);
1199 usbi_disconnect_device(dev);
1200 libusb_unref_device(dev);
1202 usbi_dbg("device not found for session %lx", session_id);
1205 usbi_mutex_static_unlock(&active_contexts_lock);
1208 #if !defined(HAVE_LIBUDEV)
1209 static int parse_u8(const char *str, uint8_t *val_p)
1215 num = strtol(str, &endptr, 10);
1216 if (num < 0 || num > UINT8_MAX || errno)
1218 if (endptr == str || *endptr != '\0')
1221 *val_p = (uint8_t)num;
1225 /* open a bus directory and adds all discovered devices to the context */
1226 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1230 struct dirent *entry;
1231 int r = LIBUSB_ERROR_IO;
1233 sprintf(dirpath, USB_DEVTMPFS_PATH "/%03u", busnum);
1234 usbi_dbg("%s", dirpath);
1235 dir = opendir(dirpath);
1237 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1238 /* FIXME: should handle valid race conditions like hub unplugged
1239 * during directory iteration - this is not an error */
1243 while ((entry = readdir(dir))) {
1246 if (entry->d_name[0] == '.')
1249 if (!parse_u8(entry->d_name, &devaddr)) {
1250 usbi_dbg("unknown dir entry %s", entry->d_name);
1254 if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1255 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1266 static int usbfs_get_device_list(struct libusb_context *ctx)
1268 struct dirent *entry;
1270 uint8_t busnum, devaddr;
1274 buses = opendir(USBDEV_PATH);
1276 buses = opendir(USB_DEVTMPFS_PATH);
1279 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1280 return LIBUSB_ERROR_IO;
1283 while ((entry = readdir(buses))) {
1284 if (entry->d_name[0] == '.')
1288 if (!_is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1291 r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1293 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1297 if (!parse_u8(entry->d_name, &busnum)) {
1298 usbi_dbg("unknown dir entry %s", entry->d_name);
1302 r = usbfs_scan_busdir(ctx, busnum);
1313 static int sysfs_get_device_list(struct libusb_context *ctx)
1315 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1316 struct dirent *entry;
1317 int num_devices = 0;
1318 int num_enumerated = 0;
1321 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1322 return LIBUSB_ERROR_IO;
1325 while ((entry = readdir(devices))) {
1326 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1327 || strchr(entry->d_name, ':'))
1332 if (sysfs_scan_device(ctx, entry->d_name)) {
1333 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1342 /* successful if at least one device was enumerated or no devices were found */
1343 if (num_enumerated || !num_devices)
1344 return LIBUSB_SUCCESS;
1346 return LIBUSB_ERROR_IO;
1349 static int linux_default_scan_devices(struct libusb_context *ctx)
1351 /* we can retrieve device list and descriptors from sysfs or usbfs.
1352 * sysfs is preferable, because if we use usbfs we end up resuming
1353 * any autosuspended USB devices. however, sysfs is not available
1354 * everywhere, so we need a usbfs fallback too.
1356 * as described in the "sysfs vs usbfs" comment at the top of this
1357 * file, sometimes we have sysfs but not enough information to
1358 * relate sysfs devices to usbfs nodes. op_init() determines the
1359 * adequacy of sysfs and sets sysfs_can_relate_devices.
1361 if (sysfs_can_relate_devices != 0)
1362 return sysfs_get_device_list(ctx);
1364 return usbfs_get_device_list(ctx);
1368 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1370 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1375 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1377 if (errno == ENOTTY)
1378 usbi_dbg("getcap not available");
1380 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1382 if (supports_flag_zero_packet)
1383 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1384 if (supports_flag_bulk_continuation)
1385 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1388 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1391 static int op_wrap_sys_device(struct libusb_context *ctx,
1392 struct libusb_device_handle *handle, intptr_t sys_dev)
1394 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1395 int fd = (int)sys_dev;
1396 uint8_t busnum, devaddr;
1397 struct usbfs_connectinfo ci;
1398 struct libusb_device *dev;
1401 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1403 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1405 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1406 return LIBUSB_ERROR_IO;
1408 /* There is no ioctl to get the bus number. We choose 0 here
1409 * as linux starts numbering buses from 1. */
1411 devaddr = ci.devnum;
1414 /* Session id is unused as we do not add the device to the list of
1415 * connected devices. */
1416 usbi_dbg("allocating new device for fd %d", fd);
1417 dev = usbi_alloc_device(ctx, 0);
1419 return LIBUSB_ERROR_NO_MEM;
1421 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1424 r = usbi_sanitize_device(dev);
1427 /* Consider the device as connected, but do not add it to the managed
1432 r = initialize_handle(handle, fd);
1437 libusb_unref_device(dev);
1441 static int op_open(struct libusb_device_handle *handle)
1445 fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1447 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1448 /* device will still be marked as attached if hotplug monitor thread
1449 * hasn't processed remove event yet */
1450 usbi_mutex_static_lock(&linux_hotplug_lock);
1451 if (handle->dev->attached) {
1452 usbi_dbg("open failed with no device, but device still attached");
1453 linux_device_disconnected(handle->dev->bus_number,
1454 handle->dev->device_address);
1456 usbi_mutex_static_unlock(&linux_hotplug_lock);
1461 r = initialize_handle(handle, fd);
1468 static void op_close(struct libusb_device_handle *dev_handle)
1470 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1472 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1473 if (!hpriv->fd_removed)
1474 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1475 if (!hpriv->fd_keep)
1479 static int op_get_configuration(struct libusb_device_handle *handle,
1482 struct linux_device_priv *priv = _device_priv(handle->dev);
1485 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1486 r = sysfs_get_active_config(handle->dev, config);
1488 r = usbfs_get_active_config(handle->dev, _device_handle_priv(handle)->fd);
1489 if (r == LIBUSB_SUCCESS)
1490 *config = priv->active_config;
1495 if (*config == -1) {
1496 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1503 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1505 struct linux_device_priv *priv = _device_priv(handle->dev);
1506 int fd = _device_handle_priv(handle)->fd;
1507 int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1510 if (errno == EINVAL)
1511 return LIBUSB_ERROR_NOT_FOUND;
1512 else if (errno == EBUSY)
1513 return LIBUSB_ERROR_BUSY;
1514 else if (errno == ENODEV)
1515 return LIBUSB_ERROR_NO_DEVICE;
1517 usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1518 return LIBUSB_ERROR_OTHER;
1521 /* update our cached active config descriptor */
1522 priv->active_config = config;
1524 return LIBUSB_SUCCESS;
1527 static int claim_interface(struct libusb_device_handle *handle, int iface)
1529 int fd = _device_handle_priv(handle)->fd;
1530 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1533 if (errno == ENOENT)
1534 return LIBUSB_ERROR_NOT_FOUND;
1535 else if (errno == EBUSY)
1536 return LIBUSB_ERROR_BUSY;
1537 else if (errno == ENODEV)
1538 return LIBUSB_ERROR_NO_DEVICE;
1540 usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1541 return LIBUSB_ERROR_OTHER;
1546 static int release_interface(struct libusb_device_handle *handle, int iface)
1548 int fd = _device_handle_priv(handle)->fd;
1549 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1552 if (errno == ENODEV)
1553 return LIBUSB_ERROR_NO_DEVICE;
1555 usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1556 return LIBUSB_ERROR_OTHER;
1561 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1564 int fd = _device_handle_priv(handle)->fd;
1565 struct usbfs_setinterface setintf;
1568 setintf.interface = iface;
1569 setintf.altsetting = altsetting;
1570 r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1572 if (errno == EINVAL)
1573 return LIBUSB_ERROR_NOT_FOUND;
1574 else if (errno == ENODEV)
1575 return LIBUSB_ERROR_NO_DEVICE;
1577 usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1578 return LIBUSB_ERROR_OTHER;
1584 static int op_clear_halt(struct libusb_device_handle *handle,
1585 unsigned char endpoint)
1587 int fd = _device_handle_priv(handle)->fd;
1588 unsigned int _endpoint = endpoint;
1589 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1592 if (errno == ENOENT)
1593 return LIBUSB_ERROR_NOT_FOUND;
1594 else if (errno == ENODEV)
1595 return LIBUSB_ERROR_NO_DEVICE;
1597 usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1598 return LIBUSB_ERROR_OTHER;
1604 static int op_reset_device(struct libusb_device_handle *handle)
1606 int fd = _device_handle_priv(handle)->fd;
1609 /* Doing a device reset will cause the usbfs driver to get unbound
1610 * from any interfaces it is bound to. By voluntarily unbinding
1611 * the usbfs driver ourself, we stop the kernel from rebinding
1612 * the interface after reset (which would end up with the interface
1613 * getting bound to the in kernel driver if any). */
1614 for (i = 0; i < USB_MAXINTERFACES; i++) {
1615 if (handle->claimed_interfaces & (1UL << i))
1616 release_interface(handle, i);
1619 usbi_mutex_lock(&handle->lock);
1620 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1622 if (errno == ENODEV) {
1623 ret = LIBUSB_ERROR_NOT_FOUND;
1627 usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1628 ret = LIBUSB_ERROR_OTHER;
1632 /* And re-claim any interfaces which were claimed before the reset */
1633 for (i = 0; i < USB_MAXINTERFACES; i++) {
1634 if (!(handle->claimed_interfaces & (1UL << i)))
1637 * A driver may have completed modprobing during
1638 * IOCTL_USBFS_RESET, and bound itself as soon as
1639 * IOCTL_USBFS_RESET released the device lock
1641 r = detach_kernel_driver_and_claim(handle, i);
1643 usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %d after reset: %s",
1644 i, libusb_error_name(r));
1645 handle->claimed_interfaces &= ~(1UL << i);
1646 ret = LIBUSB_ERROR_NOT_FOUND;
1650 usbi_mutex_unlock(&handle->lock);
1654 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1655 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1657 int r, fd = _device_handle_priv(handle)->fd;
1658 struct usbfs_streams *streams;
1660 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1661 return LIBUSB_ERROR_INVALID_PARAM;
1663 streams = malloc(sizeof(*streams) + num_endpoints);
1665 return LIBUSB_ERROR_NO_MEM;
1667 streams->num_streams = num_streams;
1668 streams->num_eps = num_endpoints;
1669 memcpy(streams->eps, endpoints, num_endpoints);
1671 r = ioctl(fd, req, streams);
1676 if (errno == ENOTTY)
1677 return LIBUSB_ERROR_NOT_SUPPORTED;
1678 else if (errno == EINVAL)
1679 return LIBUSB_ERROR_INVALID_PARAM;
1680 else if (errno == ENODEV)
1681 return LIBUSB_ERROR_NO_DEVICE;
1683 usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1684 return LIBUSB_ERROR_OTHER;
1689 static int op_alloc_streams(struct libusb_device_handle *handle,
1690 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1692 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1693 num_streams, endpoints, num_endpoints);
1696 static int op_free_streams(struct libusb_device_handle *handle,
1697 unsigned char *endpoints, int num_endpoints)
1699 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1700 endpoints, num_endpoints);
1703 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1706 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1707 unsigned char *buffer;
1709 buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1710 if (buffer == MAP_FAILED) {
1711 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1717 static int op_dev_mem_free(struct libusb_device_handle *handle,
1718 unsigned char *buffer, size_t len)
1720 if (munmap(buffer, len) != 0) {
1721 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1722 return LIBUSB_ERROR_OTHER;
1724 return LIBUSB_SUCCESS;
1728 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1731 int fd = _device_handle_priv(handle)->fd;
1732 struct usbfs_getdriver getdrv;
1735 getdrv.interface = interface;
1736 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1738 if (errno == ENODATA)
1740 else if (errno == ENODEV)
1741 return LIBUSB_ERROR_NO_DEVICE;
1743 usbi_err(HANDLE_CTX(handle), "get driver failed, errno=%d", errno);
1744 return LIBUSB_ERROR_OTHER;
1747 return strcmp(getdrv.driver, "usbfs") != 0;
1750 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1753 int fd = _device_handle_priv(handle)->fd;
1754 struct usbfs_ioctl command;
1755 struct usbfs_getdriver getdrv;
1758 command.ifno = interface;
1759 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1760 command.data = NULL;
1762 getdrv.interface = interface;
1763 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1764 if (r == 0 && !strcmp(getdrv.driver, "usbfs"))
1765 return LIBUSB_ERROR_NOT_FOUND;
1767 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1769 if (errno == ENODATA)
1770 return LIBUSB_ERROR_NOT_FOUND;
1771 else if (errno == EINVAL)
1772 return LIBUSB_ERROR_INVALID_PARAM;
1773 else if (errno == ENODEV)
1774 return LIBUSB_ERROR_NO_DEVICE;
1776 usbi_err(HANDLE_CTX(handle), "detach failed, errno=%d", errno);
1777 return LIBUSB_ERROR_OTHER;
1783 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1786 int fd = _device_handle_priv(handle)->fd;
1787 struct usbfs_ioctl command;
1790 command.ifno = interface;
1791 command.ioctl_code = IOCTL_USBFS_CONNECT;
1792 command.data = NULL;
1794 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1796 if (errno == ENODATA)
1797 return LIBUSB_ERROR_NOT_FOUND;
1798 else if (errno == EINVAL)
1799 return LIBUSB_ERROR_INVALID_PARAM;
1800 else if (errno == ENODEV)
1801 return LIBUSB_ERROR_NO_DEVICE;
1802 else if (errno == EBUSY)
1803 return LIBUSB_ERROR_BUSY;
1805 usbi_err(HANDLE_CTX(handle), "attach failed, errno=%d", errno);
1806 return LIBUSB_ERROR_OTHER;
1807 } else if (r == 0) {
1808 return LIBUSB_ERROR_NOT_FOUND;
1814 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1817 struct usbfs_disconnect_claim dc;
1818 int r, fd = _device_handle_priv(handle)->fd;
1820 dc.interface = interface;
1821 strcpy(dc.driver, "usbfs");
1822 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1823 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1830 return LIBUSB_ERROR_BUSY;
1832 return LIBUSB_ERROR_INVALID_PARAM;
1834 return LIBUSB_ERROR_NO_DEVICE;
1836 usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1837 return LIBUSB_ERROR_OTHER;
1840 /* Fallback code for kernels which don't support the
1841 disconnect-and-claim ioctl */
1842 r = op_detach_kernel_driver(handle, interface);
1843 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1846 return claim_interface(handle, interface);
1849 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1851 if (handle->auto_detach_kernel_driver)
1852 return detach_kernel_driver_and_claim(handle, iface);
1854 return claim_interface(handle, iface);
1857 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1861 r = release_interface(handle, iface);
1865 if (handle->auto_detach_kernel_driver)
1866 op_attach_kernel_driver(handle, iface);
1871 static void op_destroy_device(struct libusb_device *dev)
1873 struct linux_device_priv *priv = _device_priv(dev);
1875 free(priv->descriptors);
1876 free(priv->sysfs_dir);
1879 /* URBs are discarded in reverse order of submission to avoid races. */
1880 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1882 struct libusb_transfer *transfer =
1883 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1884 struct linux_transfer_priv *tpriv =
1885 usbi_transfer_get_os_priv(itransfer);
1886 struct linux_device_handle_priv *dpriv =
1887 _device_handle_priv(transfer->dev_handle);
1889 struct usbfs_urb *urb;
1891 for (i = last_plus_one - 1; i >= first; i--) {
1892 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1893 urb = tpriv->iso_urbs[i];
1895 urb = &tpriv->urbs[i];
1897 if (ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1900 if (errno == EINVAL) {
1901 usbi_dbg("URB not found --> assuming ready to be reaped");
1902 if (i == (last_plus_one - 1))
1903 ret = LIBUSB_ERROR_NOT_FOUND;
1904 } else if (errno == ENODEV) {
1905 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1906 ret = LIBUSB_ERROR_NO_DEVICE;
1908 usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1909 ret = LIBUSB_ERROR_OTHER;
1915 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1919 for (i = 0; i < tpriv->num_urbs; i++) {
1920 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1927 free(tpriv->iso_urbs);
1928 tpriv->iso_urbs = NULL;
1931 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1933 struct libusb_transfer *transfer =
1934 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1935 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1936 struct linux_device_handle_priv *dpriv =
1937 _device_handle_priv(transfer->dev_handle);
1938 struct usbfs_urb *urbs;
1939 int is_out = IS_XFEROUT(transfer);
1940 int bulk_buffer_len, use_bulk_continuation;
1942 int last_urb_partial = 0;
1946 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1947 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1948 return LIBUSB_ERROR_NOT_SUPPORTED;
1951 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1952 * around this by splitting large transfers into 16k blocks, and then
1953 * submit all urbs at once. it would be simpler to submit one urb at
1954 * a time, but there is a big performance gain doing it this way.
1956 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1957 * using arbritary large transfers can still be a bad idea though, as
1958 * the kernel needs to allocate physical contiguous memory for this,
1959 * which may fail for large buffers.
1961 * The kernel solves this problem by splitting the transfer into
1962 * blocks itself when the host-controller is scatter-gather capable
1963 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1965 * Last, there is the issue of short-transfers when splitting, for
1966 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1967 * is needed, but this is not always available.
1969 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1970 /* Good! Just submit everything in one go */
1971 bulk_buffer_len = transfer->length ? transfer->length : 1;
1972 use_bulk_continuation = 0;
1973 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1974 /* Split the transfers and use bulk-continuation to
1975 avoid issues with short-transfers */
1976 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1977 use_bulk_continuation = 1;
1978 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1979 /* Don't split, assume the kernel can alloc the buffer
1980 (otherwise the submit will fail with -ENOMEM) */
1981 bulk_buffer_len = transfer->length ? transfer->length : 1;
1982 use_bulk_continuation = 0;
1984 /* Bad, splitting without bulk-continuation, short transfers
1985 which end before the last urb will not work reliable! */
1986 /* Note we don't warn here as this is "normal" on kernels <
1987 2.6.32 and not a problem for most applications */
1988 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1989 use_bulk_continuation = 0;
1992 num_urbs = transfer->length / bulk_buffer_len;
1994 if (transfer->length == 0) {
1996 } else if ((transfer->length % bulk_buffer_len) > 0) {
1997 last_urb_partial = 1;
2000 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2001 urbs = calloc(num_urbs, sizeof(*urbs));
2003 return LIBUSB_ERROR_NO_MEM;
2005 tpriv->num_urbs = num_urbs;
2006 tpriv->num_retired = 0;
2007 tpriv->reap_action = NORMAL;
2008 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2010 for (i = 0; i < num_urbs; i++) {
2011 struct usbfs_urb *urb = &urbs[i];
2013 urb->usercontext = itransfer;
2014 switch (transfer->type) {
2015 case LIBUSB_TRANSFER_TYPE_BULK:
2016 urb->type = USBFS_URB_TYPE_BULK;
2019 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2020 urb->type = USBFS_URB_TYPE_BULK;
2021 urb->stream_id = itransfer->stream_id;
2023 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2024 urb->type = USBFS_URB_TYPE_INTERRUPT;
2027 urb->endpoint = transfer->endpoint;
2028 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2030 /* don't set the short not ok flag for the last URB */
2031 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2032 urb->flags = USBFS_URB_SHORT_NOT_OK;
2034 if (i == num_urbs - 1 && last_urb_partial)
2035 urb->buffer_length = transfer->length % bulk_buffer_len;
2036 else if (transfer->length == 0)
2037 urb->buffer_length = 0;
2039 urb->buffer_length = bulk_buffer_len;
2041 if (i > 0 && use_bulk_continuation)
2042 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2044 /* we have already checked that the flag is supported */
2045 if (is_out && i == num_urbs - 1 &&
2046 (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
2047 urb->flags |= USBFS_URB_ZERO_PACKET;
2049 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2053 if (errno == ENODEV) {
2054 r = LIBUSB_ERROR_NO_DEVICE;
2055 } else if (errno == ENOMEM) {
2056 r = LIBUSB_ERROR_NO_MEM;
2058 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2059 r = LIBUSB_ERROR_IO;
2062 /* if the first URB submission fails, we can simply free up and
2063 * return failure immediately. */
2065 usbi_dbg("first URB failed, easy peasy");
2071 /* if it's not the first URB that failed, the situation is a bit
2072 * tricky. we may need to discard all previous URBs. there are
2074 * - discarding is asynchronous - discarded urbs will be reaped
2075 * later. the user must not have freed the transfer when the
2076 * discarded URBs are reaped, otherwise libusb will be using
2078 * - the earlier URBs may have completed successfully and we do
2079 * not want to throw away any data.
2080 * - this URB failing may be no error; EREMOTEIO means that
2081 * this transfer simply didn't need all the URBs we submitted
2082 * so, we report that the transfer was submitted successfully and
2083 * in case of error we discard all previous URBs. later when
2084 * the final reap completes we can report error to the user,
2085 * or success if an earlier URB was completed successfully.
2087 tpriv->reap_action = errno == EREMOTEIO ? COMPLETED_EARLY : SUBMIT_FAILED;
2089 /* The URBs we haven't submitted yet we count as already
2091 tpriv->num_retired += num_urbs - i;
2093 /* If we completed short then don't try to discard. */
2094 if (tpriv->reap_action == COMPLETED_EARLY)
2097 discard_urbs(itransfer, 0, i);
2099 usbi_dbg("reporting successful submission but waiting for %d "
2100 "discards before reporting error", i);
2107 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2109 struct libusb_transfer *transfer =
2110 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2111 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2112 struct linux_device_handle_priv *dpriv =
2113 _device_handle_priv(transfer->dev_handle);
2114 struct usbfs_urb **urbs;
2115 int num_packets = transfer->num_iso_packets;
2116 int num_packets_remaining;
2119 unsigned int packet_len;
2120 unsigned int total_len = 0;
2121 unsigned char *urb_buffer = transfer->buffer;
2123 if (num_packets < 1)
2124 return LIBUSB_ERROR_INVALID_PARAM;
2126 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2127 * at least three times, but we attempt to detect this limit during
2128 * init and check it here. if the kernel rejects the request due to
2129 * its size, we return an error indicating such to the user.
2131 for (i = 0; i < num_packets; i++) {
2132 packet_len = transfer->iso_packet_desc[i].length;
2134 if (packet_len > max_iso_packet_len) {
2135 usbi_warn(TRANSFER_CTX(transfer),
2136 "iso packet length of %u bytes exceeds maximum of %u bytes",
2137 packet_len, max_iso_packet_len);
2138 return LIBUSB_ERROR_INVALID_PARAM;
2141 total_len += packet_len;
2144 if (transfer->length < (int)total_len)
2145 return LIBUSB_ERROR_INVALID_PARAM;
2147 /* usbfs limits the number of iso packets per URB */
2148 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2150 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2152 urbs = calloc(num_urbs, sizeof(*urbs));
2154 return LIBUSB_ERROR_NO_MEM;
2156 tpriv->iso_urbs = urbs;
2157 tpriv->num_urbs = num_urbs;
2158 tpriv->num_retired = 0;
2159 tpriv->reap_action = NORMAL;
2160 tpriv->iso_packet_offset = 0;
2162 /* allocate + initialize each URB with the correct number of packets */
2163 num_packets_remaining = num_packets;
2164 for (i = 0, j = 0; i < num_urbs; i++) {
2165 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2166 struct usbfs_urb *urb;
2170 alloc_size = sizeof(*urb)
2171 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2172 urb = calloc(1, alloc_size);
2174 free_iso_urbs(tpriv);
2175 return LIBUSB_ERROR_NO_MEM;
2179 /* populate packet lengths */
2180 for (k = 0; k < num_packets_in_urb; j++, k++) {
2181 packet_len = transfer->iso_packet_desc[j].length;
2182 urb->buffer_length += packet_len;
2183 urb->iso_frame_desc[k].length = packet_len;
2186 urb->usercontext = itransfer;
2187 urb->type = USBFS_URB_TYPE_ISO;
2188 /* FIXME: interface for non-ASAP data? */
2189 urb->flags = USBFS_URB_ISO_ASAP;
2190 urb->endpoint = transfer->endpoint;
2191 urb->number_of_packets = num_packets_in_urb;
2192 urb->buffer = urb_buffer;
2194 urb_buffer += urb->buffer_length;
2195 num_packets_remaining -= num_packets_in_urb;
2199 for (i = 0; i < num_urbs; i++) {
2200 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2205 if (errno == ENODEV) {
2206 r = LIBUSB_ERROR_NO_DEVICE;
2207 } else if (errno == EINVAL) {
2208 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2209 r = LIBUSB_ERROR_INVALID_PARAM;
2210 } else if (errno == EMSGSIZE) {
2211 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2212 r = LIBUSB_ERROR_INVALID_PARAM;
2214 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2215 r = LIBUSB_ERROR_IO;
2218 /* if the first URB submission fails, we can simply free up and
2219 * return failure immediately. */
2221 usbi_dbg("first URB failed, easy peasy");
2222 free_iso_urbs(tpriv);
2226 /* if it's not the first URB that failed, the situation is a bit
2227 * tricky. we must discard all previous URBs. there are
2229 * - discarding is asynchronous - discarded urbs will be reaped
2230 * later. the user must not have freed the transfer when the
2231 * discarded URBs are reaped, otherwise libusb will be using
2233 * - the earlier URBs may have completed successfully and we do
2234 * not want to throw away any data.
2235 * so, in this case we discard all the previous URBs BUT we report
2236 * that the transfer was submitted successfully. then later when
2237 * the final discard completes we can report error to the user.
2239 tpriv->reap_action = SUBMIT_FAILED;
2241 /* The URBs we haven't submitted yet we count as already
2243 tpriv->num_retired = num_urbs - i;
2244 discard_urbs(itransfer, 0, i);
2246 usbi_dbg("reporting successful submission but waiting for %d "
2247 "discards before reporting error", i);
2254 static int submit_control_transfer(struct usbi_transfer *itransfer)
2256 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2257 struct libusb_transfer *transfer =
2258 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2259 struct linux_device_handle_priv *dpriv =
2260 _device_handle_priv(transfer->dev_handle);
2261 struct usbfs_urb *urb;
2264 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2265 return LIBUSB_ERROR_INVALID_PARAM;
2267 urb = calloc(1, sizeof(*urb));
2269 return LIBUSB_ERROR_NO_MEM;
2271 tpriv->num_urbs = 1;
2272 tpriv->reap_action = NORMAL;
2274 urb->usercontext = itransfer;
2275 urb->type = USBFS_URB_TYPE_CONTROL;
2276 urb->endpoint = transfer->endpoint;
2277 urb->buffer = transfer->buffer;
2278 urb->buffer_length = transfer->length;
2280 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2284 if (errno == ENODEV)
2285 return LIBUSB_ERROR_NO_DEVICE;
2287 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2288 return LIBUSB_ERROR_IO;
2293 static int op_submit_transfer(struct usbi_transfer *itransfer)
2295 struct libusb_transfer *transfer =
2296 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2298 switch (transfer->type) {
2299 case LIBUSB_TRANSFER_TYPE_CONTROL:
2300 return submit_control_transfer(itransfer);
2301 case LIBUSB_TRANSFER_TYPE_BULK:
2302 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2303 return submit_bulk_transfer(itransfer);
2304 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2305 return submit_bulk_transfer(itransfer);
2306 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2307 return submit_iso_transfer(itransfer);
2309 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2310 return LIBUSB_ERROR_INVALID_PARAM;
2314 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2316 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2317 struct libusb_transfer *transfer =
2318 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2322 return LIBUSB_ERROR_NOT_FOUND;
2324 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2328 switch (transfer->type) {
2329 case LIBUSB_TRANSFER_TYPE_BULK:
2330 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2331 if (tpriv->reap_action == ERROR)
2333 /* else, fall through */
2335 tpriv->reap_action = CANCELLED;
2341 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2343 struct libusb_transfer *transfer =
2344 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2345 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2347 switch (transfer->type) {
2348 case LIBUSB_TRANSFER_TYPE_CONTROL:
2349 case LIBUSB_TRANSFER_TYPE_BULK:
2350 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2351 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2357 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2358 if (tpriv->iso_urbs) {
2359 free_iso_urbs(tpriv);
2360 tpriv->iso_urbs = NULL;
2364 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2368 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2369 struct usbfs_urb *urb)
2371 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2372 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2373 int urb_idx = urb - tpriv->urbs;
2375 usbi_mutex_lock(&itransfer->lock);
2376 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2377 urb_idx + 1, tpriv->num_urbs);
2379 tpriv->num_retired++;
2381 if (tpriv->reap_action != NORMAL) {
2382 /* cancelled, submit_fail, or completed early */
2383 usbi_dbg("abnormal reap: urb status %d", urb->status);
2385 /* even though we're in the process of cancelling, it's possible that
2386 * we may receive some data in these URBs that we don't want to lose.
2388 * 1. while the kernel is cancelling all the packets that make up an
2389 * URB, a few of them might complete. so we get back a successful
2390 * cancellation *and* some data.
2391 * 2. we receive a short URB which marks the early completion condition,
2392 * so we start cancelling the remaining URBs. however, we're too
2393 * slow and another URB completes (or at least completes partially).
2394 * (this can't happen since we always use BULK_CONTINUATION.)
2396 * When this happens, our objectives are not to lose any "surplus" data,
2397 * and also to stick it at the end of the previously-received data
2398 * (closing any holes), so that libusb reports the total amount of
2399 * transferred data and presents it in a contiguous chunk.
2401 if (urb->actual_length > 0) {
2402 unsigned char *target = transfer->buffer + itransfer->transferred;
2404 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2405 if (urb->buffer != target) {
2406 usbi_dbg("moving surplus data from offset %zu to offset %zu",
2407 (unsigned char *) urb->buffer - transfer->buffer,
2408 target - transfer->buffer);
2409 memmove(target, urb->buffer, urb->actual_length);
2411 itransfer->transferred += urb->actual_length;
2414 if (tpriv->num_retired == tpriv->num_urbs) {
2415 usbi_dbg("abnormal reap: last URB handled, reporting");
2416 if (tpriv->reap_action != COMPLETED_EARLY &&
2417 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2418 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2424 itransfer->transferred += urb->actual_length;
2426 /* Many of these errors can occur on *any* urb of a multi-urb
2427 * transfer. When they do, we tear down the rest of the transfer.
2429 switch (urb->status) {
2432 case -EREMOTEIO: /* short transfer */
2434 case -ENOENT: /* cancelled */
2439 usbi_dbg("device removed");
2440 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2441 goto cancel_remaining;
2443 usbi_dbg("detected endpoint stall");
2444 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2445 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2446 goto cancel_remaining;
2448 /* overflow can only ever occur in the last urb */
2449 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2450 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2451 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2458 usbi_dbg("low-level bus error %d", urb->status);
2459 tpriv->reap_action = ERROR;
2460 goto cancel_remaining;
2462 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2463 tpriv->reap_action = ERROR;
2464 goto cancel_remaining;
2467 /* if we've reaped all urbs or we got less data than requested then we're
2469 if (tpriv->num_retired == tpriv->num_urbs) {
2470 usbi_dbg("all URBs in transfer reaped --> complete!");
2472 } else if (urb->actual_length < urb->buffer_length) {
2473 usbi_dbg("short transfer %d/%d --> complete!",
2474 urb->actual_length, urb->buffer_length);
2475 if (tpriv->reap_action == NORMAL)
2476 tpriv->reap_action = COMPLETED_EARLY;
2482 if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2483 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2485 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2488 /* cancel remaining urbs and wait for their completion before
2489 * reporting results */
2490 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2493 usbi_mutex_unlock(&itransfer->lock);
2499 usbi_mutex_unlock(&itransfer->lock);
2500 return tpriv->reap_action == CANCELLED ?
2501 usbi_handle_transfer_cancellation(itransfer) :
2502 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2505 static int handle_iso_completion(struct usbi_transfer *itransfer,
2506 struct usbfs_urb *urb)
2508 struct libusb_transfer *transfer =
2509 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2510 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2511 int num_urbs = tpriv->num_urbs;
2514 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2516 usbi_mutex_lock(&itransfer->lock);
2517 for (i = 0; i < num_urbs; i++) {
2518 if (urb == tpriv->iso_urbs[i]) {
2524 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2525 usbi_mutex_unlock(&itransfer->lock);
2526 return LIBUSB_ERROR_NOT_FOUND;
2529 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2532 /* copy isochronous results back in */
2534 for (i = 0; i < urb->number_of_packets; i++) {
2535 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2536 struct libusb_iso_packet_descriptor *lib_desc =
2537 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2539 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2540 switch (urb_desc->status) {
2543 case -ENOENT: /* cancelled */
2548 usbi_dbg("packet %d - device removed", i);
2549 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2552 usbi_dbg("packet %d - detected endpoint stall", i);
2553 lib_desc->status = LIBUSB_TRANSFER_STALL;
2556 usbi_dbg("packet %d - overflow error", i);
2557 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2565 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2566 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2569 usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2570 i, urb_desc->status);
2571 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2574 lib_desc->actual_length = urb_desc->actual_length;
2577 tpriv->num_retired++;
2579 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2580 usbi_dbg("CANCEL: urb status %d", urb->status);
2582 if (tpriv->num_retired == num_urbs) {
2583 usbi_dbg("CANCEL: last URB handled, reporting");
2584 free_iso_urbs(tpriv);
2585 if (tpriv->reap_action == CANCELLED) {
2586 usbi_mutex_unlock(&itransfer->lock);
2587 return usbi_handle_transfer_cancellation(itransfer);
2589 usbi_mutex_unlock(&itransfer->lock);
2590 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2596 switch (urb->status) {
2599 case -ENOENT: /* cancelled */
2603 usbi_dbg("device removed");
2604 status = LIBUSB_TRANSFER_NO_DEVICE;
2607 usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2608 status = LIBUSB_TRANSFER_ERROR;
2612 /* if we've reaped all urbs then we're done */
2613 if (tpriv->num_retired == num_urbs) {
2614 usbi_dbg("all URBs in transfer reaped --> complete!");
2615 free_iso_urbs(tpriv);
2616 usbi_mutex_unlock(&itransfer->lock);
2617 return usbi_handle_transfer_completion(itransfer, status);
2621 usbi_mutex_unlock(&itransfer->lock);
2625 static int handle_control_completion(struct usbi_transfer *itransfer,
2626 struct usbfs_urb *urb)
2628 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2631 usbi_mutex_lock(&itransfer->lock);
2632 usbi_dbg("handling completion status %d", urb->status);
2634 itransfer->transferred += urb->actual_length;
2636 if (tpriv->reap_action == CANCELLED) {
2637 if (urb->status && urb->status != -ENOENT)
2638 usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2642 usbi_mutex_unlock(&itransfer->lock);
2643 return usbi_handle_transfer_cancellation(itransfer);
2646 switch (urb->status) {
2648 status = LIBUSB_TRANSFER_COMPLETED;
2650 case -ENOENT: /* cancelled */
2651 status = LIBUSB_TRANSFER_CANCELLED;
2655 usbi_dbg("device removed");
2656 status = LIBUSB_TRANSFER_NO_DEVICE;
2659 usbi_dbg("unsupported control request");
2660 status = LIBUSB_TRANSFER_STALL;
2663 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2664 status = LIBUSB_TRANSFER_OVERFLOW;
2671 usbi_dbg("low-level bus error %d", urb->status);
2672 status = LIBUSB_TRANSFER_ERROR;
2675 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2676 status = LIBUSB_TRANSFER_ERROR;
2682 usbi_mutex_unlock(&itransfer->lock);
2683 return usbi_handle_transfer_completion(itransfer, status);
2686 static int reap_for_handle(struct libusb_device_handle *handle)
2688 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2690 struct usbfs_urb *urb = NULL;
2691 struct usbi_transfer *itransfer;
2692 struct libusb_transfer *transfer;
2694 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2696 if (errno == EAGAIN)
2698 if (errno == ENODEV)
2699 return LIBUSB_ERROR_NO_DEVICE;
2701 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2702 return LIBUSB_ERROR_IO;
2705 itransfer = urb->usercontext;
2706 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2708 usbi_dbg("urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2710 switch (transfer->type) {
2711 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2712 return handle_iso_completion(itransfer, urb);
2713 case LIBUSB_TRANSFER_TYPE_BULK:
2714 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2715 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2716 return handle_bulk_completion(itransfer, urb);
2717 case LIBUSB_TRANSFER_TYPE_CONTROL:
2718 return handle_control_completion(itransfer, urb);
2720 usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2721 return LIBUSB_ERROR_OTHER;
2725 static int op_handle_events(struct libusb_context *ctx,
2726 struct pollfd *fds, usbi_nfds_t nfds, int num_ready)
2731 usbi_mutex_lock(&ctx->open_devs_lock);
2732 for (n = 0; n < nfds && num_ready > 0; n++) {
2733 struct pollfd *pollfd = &fds[n];
2734 struct libusb_device_handle *handle;
2735 struct linux_device_handle_priv *hpriv = NULL;
2737 if (!pollfd->revents)
2741 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2742 hpriv = _device_handle_priv(handle);
2743 if (hpriv->fd == pollfd->fd)
2747 if (!hpriv || hpriv->fd != pollfd->fd) {
2748 usbi_err(ctx, "cannot find handle for fd %d",
2753 if (pollfd->revents & POLLERR) {
2754 /* remove the fd from the pollfd set so that it doesn't continuously
2755 * trigger an event, and flag that it has been removed so op_close()
2756 * doesn't try to remove it a second time */
2757 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2758 hpriv->fd_removed = 1;
2760 /* device will still be marked as attached if hotplug monitor thread
2761 * hasn't processed remove event yet */
2762 usbi_mutex_static_lock(&linux_hotplug_lock);
2763 if (handle->dev->attached)
2764 linux_device_disconnected(handle->dev->bus_number,
2765 handle->dev->device_address);
2766 usbi_mutex_static_unlock(&linux_hotplug_lock);
2768 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2770 r = reap_for_handle(handle);
2774 usbi_handle_disconnect(handle);
2779 r = reap_for_handle(handle);
2781 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2789 usbi_mutex_unlock(&ctx->open_devs_lock);
2793 static int op_clock_gettime(int clk_id, struct timespec *tp)
2796 case USBI_CLOCK_MONOTONIC:
2797 return clock_gettime(monotonic_clkid, tp);
2798 case USBI_CLOCK_REALTIME:
2799 return clock_gettime(CLOCK_REALTIME, tp);
2801 return LIBUSB_ERROR_INVALID_PARAM;
2806 static clockid_t op_get_timerfd_clockid(void)
2808 return monotonic_clkid;
2813 const struct usbi_os_backend usbi_backend = {
2814 .name = "Linux usbfs",
2815 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2818 .hotplug_poll = op_hotplug_poll,
2819 .get_device_descriptor = op_get_device_descriptor,
2820 .get_active_config_descriptor = op_get_active_config_descriptor,
2821 .get_config_descriptor = op_get_config_descriptor,
2822 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2824 .wrap_sys_device = op_wrap_sys_device,
2827 .get_configuration = op_get_configuration,
2828 .set_configuration = op_set_configuration,
2829 .claim_interface = op_claim_interface,
2830 .release_interface = op_release_interface,
2832 .set_interface_altsetting = op_set_interface,
2833 .clear_halt = op_clear_halt,
2834 .reset_device = op_reset_device,
2836 .alloc_streams = op_alloc_streams,
2837 .free_streams = op_free_streams,
2839 .dev_mem_alloc = op_dev_mem_alloc,
2840 .dev_mem_free = op_dev_mem_free,
2842 .kernel_driver_active = op_kernel_driver_active,
2843 .detach_kernel_driver = op_detach_kernel_driver,
2844 .attach_kernel_driver = op_attach_kernel_driver,
2846 .destroy_device = op_destroy_device,
2848 .submit_transfer = op_submit_transfer,
2849 .cancel_transfer = op_cancel_transfer,
2850 .clear_transfer_priv = op_clear_transfer_priv,
2852 .handle_events = op_handle_events,
2854 .clock_gettime = op_clock_gettime,
2857 .get_timerfd_clockid = op_get_timerfd_clockid,
2860 .device_priv_size = sizeof(struct linux_device_priv),
2861 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2862 .transfer_priv_size = sizeof(struct linux_transfer_priv),