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);
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, errno=%d", filename, 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, errno=%d", 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, errno=%d", 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, "lseek failed, errno=%d", 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, errno=%d", errno);
1034 if (fd != wrapped_fd)
1036 return LIBUSB_ERROR_IO;
1038 priv->descriptors_len += r;
1039 } while (priv->descriptors_len == descriptors_size);
1041 if (fd != wrapped_fd)
1044 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1045 usbi_err(ctx, "short descriptor read (%d)",
1046 priv->descriptors_len);
1047 return LIBUSB_ERROR_IO;
1050 if (sysfs_dir && sysfs_can_relate_devices)
1052 if (fd != wrapped_fd)
1054 return LIBUSB_SUCCESS;
1057 /* cache active config */
1059 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1063 /* cannot send a control message to determine the active
1064 * config. just assume the first one is active. */
1065 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1066 "active configuration descriptor");
1067 if (priv->descriptors_len >=
1068 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1069 struct libusb_config_descriptor config;
1070 usbi_parse_descriptor(
1071 priv->descriptors + DEVICE_DESC_LENGTH,
1072 "bbwbbbbb", &config, 0);
1073 priv->active_config = config.bConfigurationValue;
1075 priv->active_config = -1; /* No config dt */
1077 return LIBUSB_SUCCESS;
1080 r = usbfs_get_active_config(dev, fd);
1087 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1089 struct libusb_context *ctx = DEVICE_CTX(dev);
1090 struct libusb_device *it;
1091 char *parent_sysfs_dir, *tmp;
1092 int ret, add_parent = 1;
1094 /* XXX -- can we figure out the topology when using usbfs? */
1095 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1096 /* either using usbfs or finding the parent of a root hub */
1097 return LIBUSB_SUCCESS;
1100 parent_sysfs_dir = strdup(sysfs_dir);
1101 if (NULL == parent_sysfs_dir) {
1102 return LIBUSB_ERROR_NO_MEM;
1104 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1105 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1106 dev->port_number = atoi(tmp + 1);
1109 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1111 free (parent_sysfs_dir);
1112 return LIBUSB_SUCCESS;
1115 /* is the parent a root hub? */
1116 if (NULL == strchr(parent_sysfs_dir, '-')) {
1117 tmp = parent_sysfs_dir;
1118 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1121 return LIBUSB_ERROR_NO_MEM;
1126 /* find the parent in the context */
1127 usbi_mutex_lock(&ctx->usb_devs_lock);
1128 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1129 struct linux_device_priv *priv = _device_priv(it);
1130 if (priv->sysfs_dir) {
1131 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1132 dev->parent_dev = libusb_ref_device(it);
1137 usbi_mutex_unlock(&ctx->usb_devs_lock);
1139 if (!dev->parent_dev && add_parent) {
1140 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1142 sysfs_scan_device(ctx, parent_sysfs_dir);
1147 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1148 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1150 free (parent_sysfs_dir);
1152 return LIBUSB_SUCCESS;
1155 int linux_enumerate_device(struct libusb_context *ctx,
1156 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1158 unsigned long session_id;
1159 struct libusb_device *dev;
1162 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1163 * will be reused. instead we should add a simple sysfs attribute with
1165 session_id = busnum << 8 | devaddr;
1166 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1169 dev = usbi_get_device_by_session_id(ctx, session_id);
1171 /* device already exists in the context */
1172 usbi_dbg("session_id %ld already exists", session_id);
1173 libusb_unref_device(dev);
1174 return LIBUSB_SUCCESS;
1177 usbi_dbg("allocating new device for %d/%d (session %ld)",
1178 busnum, devaddr, session_id);
1179 dev = usbi_alloc_device(ctx, session_id);
1181 return LIBUSB_ERROR_NO_MEM;
1183 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1186 r = usbi_sanitize_device(dev);
1190 r = linux_get_parent_info(dev, sysfs_dir);
1195 libusb_unref_device(dev);
1197 usbi_connect_device(dev);
1202 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1204 struct libusb_context *ctx;
1206 usbi_mutex_static_lock(&active_contexts_lock);
1207 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1208 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1210 usbi_mutex_static_unlock(&active_contexts_lock);
1213 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1215 struct libusb_context *ctx;
1216 struct libusb_device *dev;
1217 unsigned long session_id = busnum << 8 | devaddr;
1219 usbi_mutex_static_lock(&active_contexts_lock);
1220 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1221 dev = usbi_get_device_by_session_id (ctx, session_id);
1223 usbi_disconnect_device (dev);
1224 libusb_unref_device(dev);
1226 usbi_dbg("device not found for session %lx", session_id);
1229 usbi_mutex_static_unlock(&active_contexts_lock);
1232 #if !defined(USE_UDEV)
1233 /* open a bus directory and adds all discovered devices to the context */
1234 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1237 char dirpath[PATH_MAX];
1238 struct dirent *entry;
1239 int r = LIBUSB_ERROR_IO;
1241 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1242 usbi_dbg("%s", dirpath);
1243 dir = opendir(dirpath);
1245 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1246 /* FIXME: should handle valid race conditions like hub unplugged
1247 * during directory iteration - this is not an error */
1251 while ((entry = readdir(dir))) {
1254 if (entry->d_name[0] == '.')
1257 devaddr = atoi(entry->d_name);
1259 usbi_dbg("unknown dir entry %s", entry->d_name);
1263 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1264 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1275 static int usbfs_get_device_list(struct libusb_context *ctx)
1277 struct dirent *entry;
1278 DIR *buses = opendir(usbfs_path);
1282 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1283 return LIBUSB_ERROR_IO;
1286 while ((entry = readdir(buses))) {
1289 if (entry->d_name[0] == '.')
1294 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1297 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1299 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1303 busnum = atoi(entry->d_name);
1305 usbi_dbg("unknown dir entry %s", entry->d_name);
1309 r = usbfs_scan_busdir(ctx, busnum);
1321 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1323 uint8_t busnum, devaddr;
1326 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname, -1);
1327 if (LIBUSB_SUCCESS != ret) {
1331 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1335 #if !defined(USE_UDEV)
1336 static int sysfs_get_device_list(struct libusb_context *ctx)
1338 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1339 struct dirent *entry;
1340 int num_devices = 0;
1341 int num_enumerated = 0;
1344 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1345 return LIBUSB_ERROR_IO;
1348 while ((entry = readdir(devices))) {
1349 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1350 || strchr(entry->d_name, ':'))
1355 if (sysfs_scan_device(ctx, entry->d_name)) {
1356 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1365 /* successful if at least one device was enumerated or no devices were found */
1366 if (num_enumerated || !num_devices)
1367 return LIBUSB_SUCCESS;
1369 return LIBUSB_ERROR_IO;
1372 static int linux_default_scan_devices (struct libusb_context *ctx)
1374 /* we can retrieve device list and descriptors from sysfs or usbfs.
1375 * sysfs is preferable, because if we use usbfs we end up resuming
1376 * any autosuspended USB devices. however, sysfs is not available
1377 * everywhere, so we need a usbfs fallback too.
1379 * as described in the "sysfs vs usbfs" comment at the top of this
1380 * file, sometimes we have sysfs but not enough information to
1381 * relate sysfs devices to usbfs nodes. op_init() determines the
1382 * adequacy of sysfs and sets sysfs_can_relate_devices.
1384 if (sysfs_can_relate_devices != 0)
1385 return sysfs_get_device_list(ctx);
1387 return usbfs_get_device_list(ctx);
1391 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1393 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1398 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1400 if (errno == ENOTTY)
1401 usbi_dbg("getcap not available");
1403 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1405 if (supports_flag_zero_packet)
1406 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1407 if (supports_flag_bulk_continuation)
1408 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1411 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1414 static int op_wrap_sys_device(struct libusb_context *ctx,
1415 struct libusb_device_handle *handle, intptr_t sys_dev)
1417 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1418 int fd = (int)sys_dev;
1419 uint8_t busnum, devaddr;
1420 struct usbfs_connectinfo ci;
1421 struct libusb_device *dev;
1424 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1426 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1428 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1429 return LIBUSB_ERROR_IO;
1431 /* There is no ioctl to get the bus number. We choose 0 here
1432 * as linux starts numbering buses from 1. */
1434 devaddr = ci.devnum;
1437 /* Session id is unused as we do not add the device to the list of
1438 * connected devices. */
1439 usbi_dbg("allocating new device for fd %d", fd);
1440 dev = usbi_alloc_device(ctx, 0);
1442 return LIBUSB_ERROR_NO_MEM;
1444 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1447 r = usbi_sanitize_device(dev);
1450 /* Consider the device as connected, but do not add it to the managed
1455 r = initialize_handle(handle, fd);
1460 libusb_unref_device(dev);
1464 static int op_open(struct libusb_device_handle *handle)
1468 fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1470 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1471 /* device will still be marked as attached if hotplug monitor thread
1472 * hasn't processed remove event yet */
1473 usbi_mutex_static_lock(&linux_hotplug_lock);
1474 if (handle->dev->attached) {
1475 usbi_dbg("open failed with no device, but device still attached");
1476 linux_device_disconnected(handle->dev->bus_number,
1477 handle->dev->device_address);
1479 usbi_mutex_static_unlock(&linux_hotplug_lock);
1484 r = initialize_handle(handle, fd);
1491 static void op_close(struct libusb_device_handle *dev_handle)
1493 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1494 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1495 if (!hpriv->fd_removed)
1496 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1497 if (!hpriv->fd_keep)
1501 static int op_get_configuration(struct libusb_device_handle *handle,
1504 struct linux_device_priv *priv = _device_priv(handle->dev);
1507 if (priv->sysfs_dir && sysfs_can_relate_devices) {
1508 r = sysfs_get_active_config(handle->dev, config);
1510 r = usbfs_get_active_config(handle->dev,
1511 _device_handle_priv(handle)->fd);
1512 if (r == LIBUSB_SUCCESS)
1513 *config = priv->active_config;
1518 if (*config == -1) {
1519 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1526 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1528 struct linux_device_priv *priv = _device_priv(handle->dev);
1529 int fd = _device_handle_priv(handle)->fd;
1530 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1532 if (errno == EINVAL)
1533 return LIBUSB_ERROR_NOT_FOUND;
1534 else if (errno == EBUSY)
1535 return LIBUSB_ERROR_BUSY;
1536 else if (errno == ENODEV)
1537 return LIBUSB_ERROR_NO_DEVICE;
1539 usbi_err(HANDLE_CTX(handle),
1540 "set configuration failed, errno=%d", errno);
1541 return LIBUSB_ERROR_OTHER;
1544 /* update our cached active config descriptor */
1545 priv->active_config = config;
1547 return LIBUSB_SUCCESS;
1550 static int claim_interface(struct libusb_device_handle *handle, int iface)
1552 int fd = _device_handle_priv(handle)->fd;
1553 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1555 if (errno == ENOENT)
1556 return LIBUSB_ERROR_NOT_FOUND;
1557 else if (errno == EBUSY)
1558 return LIBUSB_ERROR_BUSY;
1559 else if (errno == ENODEV)
1560 return LIBUSB_ERROR_NO_DEVICE;
1562 usbi_err(HANDLE_CTX(handle),
1563 "claim interface failed, errno=%d", errno);
1564 return LIBUSB_ERROR_OTHER;
1569 static int release_interface(struct libusb_device_handle *handle, int iface)
1571 int fd = _device_handle_priv(handle)->fd;
1572 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1574 if (errno == ENODEV)
1575 return LIBUSB_ERROR_NO_DEVICE;
1577 usbi_err(HANDLE_CTX(handle),
1578 "release interface failed, errno=%d", errno);
1579 return LIBUSB_ERROR_OTHER;
1584 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1587 int fd = _device_handle_priv(handle)->fd;
1588 struct usbfs_setinterface setintf;
1591 setintf.interface = iface;
1592 setintf.altsetting = altsetting;
1593 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1595 if (errno == EINVAL)
1596 return LIBUSB_ERROR_NOT_FOUND;
1597 else if (errno == ENODEV)
1598 return LIBUSB_ERROR_NO_DEVICE;
1600 usbi_err(HANDLE_CTX(handle),
1601 "set interface failed, errno=%d", errno);
1602 return LIBUSB_ERROR_OTHER;
1608 static int op_clear_halt(struct libusb_device_handle *handle,
1609 unsigned char endpoint)
1611 int fd = _device_handle_priv(handle)->fd;
1612 unsigned int _endpoint = endpoint;
1613 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1615 if (errno == ENOENT)
1616 return LIBUSB_ERROR_NOT_FOUND;
1617 else if (errno == ENODEV)
1618 return LIBUSB_ERROR_NO_DEVICE;
1620 usbi_err(HANDLE_CTX(handle),
1621 "clear halt failed, errno=%d", errno);
1622 return LIBUSB_ERROR_OTHER;
1628 static int op_reset_device(struct libusb_device_handle *handle)
1630 int fd = _device_handle_priv(handle)->fd;
1633 /* Doing a device reset will cause the usbfs driver to get unbound
1634 from any interfaces it is bound to. By voluntarily unbinding
1635 the usbfs driver ourself, we stop the kernel from rebinding
1636 the interface after reset (which would end up with the interface
1637 getting bound to the in kernel driver if any). */
1638 for (i = 0; i < USB_MAXINTERFACES; i++) {
1639 if (handle->claimed_interfaces & (1L << i)) {
1640 release_interface(handle, i);
1644 usbi_mutex_lock(&handle->lock);
1645 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1647 if (errno == ENODEV) {
1648 ret = LIBUSB_ERROR_NOT_FOUND;
1652 usbi_err(HANDLE_CTX(handle),
1653 "reset failed, errno=%d", errno);
1654 ret = LIBUSB_ERROR_OTHER;
1658 /* And re-claim any interfaces which were claimed before the reset */
1659 for (i = 0; i < USB_MAXINTERFACES; i++) {
1660 if (handle->claimed_interfaces & (1L << i)) {
1662 * A driver may have completed modprobing during
1663 * IOCTL_USBFS_RESET, and bound itself as soon as
1664 * IOCTL_USBFS_RESET released the device lock
1666 r = detach_kernel_driver_and_claim(handle, i);
1668 usbi_warn(HANDLE_CTX(handle),
1669 "failed to re-claim interface %d after reset: %s",
1670 i, libusb_error_name(r));
1671 handle->claimed_interfaces &= ~(1L << i);
1672 ret = LIBUSB_ERROR_NOT_FOUND;
1677 usbi_mutex_unlock(&handle->lock);
1681 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1682 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1684 int r, fd = _device_handle_priv(handle)->fd;
1685 struct usbfs_streams *streams;
1687 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1688 return LIBUSB_ERROR_INVALID_PARAM;
1690 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1692 return LIBUSB_ERROR_NO_MEM;
1694 streams->num_streams = num_streams;
1695 streams->num_eps = num_endpoints;
1696 memcpy(streams->eps, endpoints, num_endpoints);
1698 r = ioctl(fd, req, streams);
1703 if (errno == ENOTTY)
1704 return LIBUSB_ERROR_NOT_SUPPORTED;
1705 else if (errno == EINVAL)
1706 return LIBUSB_ERROR_INVALID_PARAM;
1707 else if (errno == ENODEV)
1708 return LIBUSB_ERROR_NO_DEVICE;
1710 usbi_err(HANDLE_CTX(handle),
1711 "streams-ioctl failed, errno=%d", errno);
1712 return LIBUSB_ERROR_OTHER;
1717 static int op_alloc_streams(struct libusb_device_handle *handle,
1718 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1720 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1721 num_streams, endpoints, num_endpoints);
1724 static int op_free_streams(struct libusb_device_handle *handle,
1725 unsigned char *endpoints, int num_endpoints)
1727 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1728 endpoints, num_endpoints);
1731 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1734 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1735 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1736 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1737 if (buffer == MAP_FAILED) {
1738 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d",
1745 static int op_dev_mem_free(struct libusb_device_handle *handle,
1746 unsigned char *buffer, size_t len)
1748 if (munmap(buffer, len) != 0) {
1749 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d",
1751 return LIBUSB_ERROR_OTHER;
1753 return LIBUSB_SUCCESS;
1757 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1760 int fd = _device_handle_priv(handle)->fd;
1761 struct usbfs_getdriver getdrv;
1764 getdrv.interface = interface;
1765 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1767 if (errno == ENODATA)
1769 else if (errno == ENODEV)
1770 return LIBUSB_ERROR_NO_DEVICE;
1772 usbi_err(HANDLE_CTX(handle),
1773 "get driver failed, errno=%d", errno);
1774 return LIBUSB_ERROR_OTHER;
1777 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1780 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1783 int fd = _device_handle_priv(handle)->fd;
1784 struct usbfs_ioctl command;
1785 struct usbfs_getdriver getdrv;
1788 command.ifno = interface;
1789 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1790 command.data = NULL;
1792 getdrv.interface = interface;
1793 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1794 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1795 return LIBUSB_ERROR_NOT_FOUND;
1797 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1799 if (errno == ENODATA)
1800 return LIBUSB_ERROR_NOT_FOUND;
1801 else if (errno == EINVAL)
1802 return LIBUSB_ERROR_INVALID_PARAM;
1803 else if (errno == ENODEV)
1804 return LIBUSB_ERROR_NO_DEVICE;
1806 usbi_err(HANDLE_CTX(handle),
1807 "detach failed, errno=%d", errno);
1808 return LIBUSB_ERROR_OTHER;
1814 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1817 int fd = _device_handle_priv(handle)->fd;
1818 struct usbfs_ioctl command;
1821 command.ifno = interface;
1822 command.ioctl_code = IOCTL_USBFS_CONNECT;
1823 command.data = NULL;
1825 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1827 if (errno == ENODATA)
1828 return LIBUSB_ERROR_NOT_FOUND;
1829 else if (errno == EINVAL)
1830 return LIBUSB_ERROR_INVALID_PARAM;
1831 else if (errno == ENODEV)
1832 return LIBUSB_ERROR_NO_DEVICE;
1833 else if (errno == EBUSY)
1834 return LIBUSB_ERROR_BUSY;
1836 usbi_err(HANDLE_CTX(handle),
1837 "attach failed, errno=%d", errno);
1838 return LIBUSB_ERROR_OTHER;
1839 } else if (r == 0) {
1840 return LIBUSB_ERROR_NOT_FOUND;
1846 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1849 struct usbfs_disconnect_claim dc;
1850 int r, fd = _device_handle_priv(handle)->fd;
1852 dc.interface = interface;
1853 strcpy(dc.driver, "usbfs");
1854 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1855 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1856 if (r != 0 && errno != ENOTTY) {
1859 return LIBUSB_ERROR_BUSY;
1861 return LIBUSB_ERROR_INVALID_PARAM;
1863 return LIBUSB_ERROR_NO_DEVICE;
1865 usbi_err(HANDLE_CTX(handle),
1866 "disconnect-and-claim failed, errno=%d", errno);
1867 return LIBUSB_ERROR_OTHER;
1871 /* Fallback code for kernels which don't support the
1872 disconnect-and-claim ioctl */
1873 r = op_detach_kernel_driver(handle, interface);
1874 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1877 return claim_interface(handle, interface);
1880 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1882 if (handle->auto_detach_kernel_driver)
1883 return detach_kernel_driver_and_claim(handle, iface);
1885 return claim_interface(handle, iface);
1888 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1892 r = release_interface(handle, iface);
1896 if (handle->auto_detach_kernel_driver)
1897 op_attach_kernel_driver(handle, iface);
1902 static void op_destroy_device(struct libusb_device *dev)
1904 struct linux_device_priv *priv = _device_priv(dev);
1905 if (priv->descriptors)
1906 free(priv->descriptors);
1907 if (priv->sysfs_dir)
1908 free(priv->sysfs_dir);
1911 /* URBs are discarded in reverse order of submission to avoid races. */
1912 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1914 struct libusb_transfer *transfer =
1915 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1916 struct linux_transfer_priv *tpriv =
1917 usbi_transfer_get_os_priv(itransfer);
1918 struct linux_device_handle_priv *dpriv =
1919 _device_handle_priv(transfer->dev_handle);
1921 struct usbfs_urb *urb;
1923 for (i = last_plus_one - 1; i >= first; i--) {
1924 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1925 urb = tpriv->iso_urbs[i];
1927 urb = &tpriv->urbs[i];
1929 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1932 if (EINVAL == errno) {
1933 usbi_dbg("URB not found --> assuming ready to be reaped");
1934 if (i == (last_plus_one - 1))
1935 ret = LIBUSB_ERROR_NOT_FOUND;
1936 } else if (ENODEV == errno) {
1937 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1938 ret = LIBUSB_ERROR_NO_DEVICE;
1940 usbi_warn(TRANSFER_CTX(transfer),
1941 "unrecognised discard errno %d", errno);
1942 ret = LIBUSB_ERROR_OTHER;
1948 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1951 for (i = 0; i < tpriv->num_urbs; i++) {
1952 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1958 free(tpriv->iso_urbs);
1959 tpriv->iso_urbs = NULL;
1962 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1964 struct libusb_transfer *transfer =
1965 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1966 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1967 struct linux_device_handle_priv *dpriv =
1968 _device_handle_priv(transfer->dev_handle);
1969 struct usbfs_urb *urbs;
1970 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1971 == LIBUSB_ENDPOINT_OUT;
1972 int bulk_buffer_len, use_bulk_continuation;
1976 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1977 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1978 return LIBUSB_ERROR_NOT_SUPPORTED;
1981 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1982 * around this by splitting large transfers into 16k blocks, and then
1983 * submit all urbs at once. it would be simpler to submit one urb at
1984 * a time, but there is a big performance gain doing it this way.
1986 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1987 * using arbritary large transfers can still be a bad idea though, as
1988 * the kernel needs to allocate physical contiguous memory for this,
1989 * which may fail for large buffers.
1991 * The kernel solves this problem by splitting the transfer into
1992 * blocks itself when the host-controller is scatter-gather capable
1993 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1995 * Last, there is the issue of short-transfers when splitting, for
1996 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1997 * is needed, but this is not always available.
1999 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
2000 /* Good! Just submit everything in one go */
2001 bulk_buffer_len = transfer->length ? transfer->length : 1;
2002 use_bulk_continuation = 0;
2003 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
2004 /* Split the transfers and use bulk-continuation to
2005 avoid issues with short-transfers */
2006 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2007 use_bulk_continuation = 1;
2008 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
2009 /* Don't split, assume the kernel can alloc the buffer
2010 (otherwise the submit will fail with -ENOMEM) */
2011 bulk_buffer_len = transfer->length ? transfer->length : 1;
2012 use_bulk_continuation = 0;
2014 /* Bad, splitting without bulk-continuation, short transfers
2015 which end before the last urb will not work reliable! */
2016 /* Note we don't warn here as this is "normal" on kernels <
2017 2.6.32 and not a problem for most applications */
2018 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2019 use_bulk_continuation = 0;
2022 int num_urbs = transfer->length / bulk_buffer_len;
2023 int last_urb_partial = 0;
2025 if (transfer->length == 0) {
2027 } else if ((transfer->length % bulk_buffer_len) > 0) {
2028 last_urb_partial = 1;
2031 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2033 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2035 return LIBUSB_ERROR_NO_MEM;
2037 tpriv->num_urbs = num_urbs;
2038 tpriv->num_retired = 0;
2039 tpriv->reap_action = NORMAL;
2040 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2042 for (i = 0; i < num_urbs; i++) {
2043 struct usbfs_urb *urb = &urbs[i];
2044 urb->usercontext = itransfer;
2045 switch (transfer->type) {
2046 case LIBUSB_TRANSFER_TYPE_BULK:
2047 urb->type = USBFS_URB_TYPE_BULK;
2050 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2051 urb->type = USBFS_URB_TYPE_BULK;
2052 urb->stream_id = itransfer->stream_id;
2054 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2055 urb->type = USBFS_URB_TYPE_INTERRUPT;
2058 urb->endpoint = transfer->endpoint;
2059 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2060 /* don't set the short not ok flag for the last URB */
2061 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2062 urb->flags = USBFS_URB_SHORT_NOT_OK;
2063 if (i == num_urbs - 1 && last_urb_partial)
2064 urb->buffer_length = transfer->length % bulk_buffer_len;
2065 else if (transfer->length == 0)
2066 urb->buffer_length = 0;
2068 urb->buffer_length = bulk_buffer_len;
2070 if (i > 0 && use_bulk_continuation)
2071 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2073 /* we have already checked that the flag is supported */
2074 if (is_out && i == num_urbs - 1 &&
2075 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2076 urb->flags |= USBFS_URB_ZERO_PACKET;
2078 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2080 if (errno == ENODEV) {
2081 r = LIBUSB_ERROR_NO_DEVICE;
2082 } else if (errno == ENOMEM) {
2083 r = LIBUSB_ERROR_NO_MEM;
2085 usbi_err(TRANSFER_CTX(transfer),
2086 "submiturb failed, errno=%d", errno);
2087 r = LIBUSB_ERROR_IO;
2090 /* if the first URB submission fails, we can simply free up and
2091 * return failure immediately. */
2093 usbi_dbg("first URB failed, easy peasy");
2099 /* if it's not the first URB that failed, the situation is a bit
2100 * tricky. we may need to discard all previous URBs. there are
2102 * - discarding is asynchronous - discarded urbs will be reaped
2103 * later. the user must not have freed the transfer when the
2104 * discarded URBs are reaped, otherwise libusb will be using
2106 * - the earlier URBs may have completed successfully and we do
2107 * not want to throw away any data.
2108 * - this URB failing may be no error; EREMOTEIO means that
2109 * this transfer simply didn't need all the URBs we submitted
2110 * so, we report that the transfer was submitted successfully and
2111 * in case of error we discard all previous URBs. later when
2112 * the final reap completes we can report error to the user,
2113 * or success if an earlier URB was completed successfully.
2115 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2117 /* The URBs we haven't submitted yet we count as already
2119 tpriv->num_retired += num_urbs - i;
2121 /* If we completed short then don't try to discard. */
2122 if (COMPLETED_EARLY == tpriv->reap_action)
2125 discard_urbs(itransfer, 0, i);
2127 usbi_dbg("reporting successful submission but waiting for %d "
2128 "discards before reporting error", i);
2136 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2138 struct libusb_transfer *transfer =
2139 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2140 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2141 struct linux_device_handle_priv *dpriv =
2142 _device_handle_priv(transfer->dev_handle);
2143 struct usbfs_urb **urbs;
2144 int num_packets = transfer->num_iso_packets;
2145 int num_packets_remaining;
2148 unsigned int packet_len;
2149 unsigned int total_len = 0;
2150 unsigned char *urb_buffer = transfer->buffer;
2152 if (num_packets < 1)
2153 return LIBUSB_ERROR_INVALID_PARAM;
2155 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2156 * at least three times, but we attempt to detect this limit during
2157 * init and check it here. if the kernel rejects the request due to
2158 * its size, we return an error indicating such to the user.
2160 for (i = 0; i < num_packets; i++) {
2161 packet_len = transfer->iso_packet_desc[i].length;
2163 if (packet_len > max_iso_packet_len) {
2164 usbi_warn(TRANSFER_CTX(transfer),
2165 "iso packet length of %u bytes exceeds maximum of %u bytes",
2166 packet_len, max_iso_packet_len);
2167 return LIBUSB_ERROR_INVALID_PARAM;
2170 total_len += packet_len;
2173 if (transfer->length < (int)total_len)
2174 return LIBUSB_ERROR_INVALID_PARAM;
2176 /* usbfs limits the number of iso packets per URB */
2177 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2179 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2182 urbs = calloc(num_urbs, sizeof(*urbs));
2184 return LIBUSB_ERROR_NO_MEM;
2186 tpriv->iso_urbs = urbs;
2187 tpriv->num_urbs = num_urbs;
2188 tpriv->num_retired = 0;
2189 tpriv->reap_action = NORMAL;
2190 tpriv->iso_packet_offset = 0;
2192 /* allocate + initialize each URB with the correct number of packets */
2193 num_packets_remaining = num_packets;
2194 for (i = 0, j = 0; i < num_urbs; i++) {
2195 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2196 struct usbfs_urb *urb;
2200 alloc_size = sizeof(*urb)
2201 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2202 urb = calloc(1, alloc_size);
2204 free_iso_urbs(tpriv);
2205 return LIBUSB_ERROR_NO_MEM;
2209 /* populate packet lengths */
2210 for (k = 0; k < num_packets_in_urb; j++, k++) {
2211 packet_len = transfer->iso_packet_desc[j].length;
2212 urb->buffer_length += packet_len;
2213 urb->iso_frame_desc[k].length = packet_len;
2216 urb->usercontext = itransfer;
2217 urb->type = USBFS_URB_TYPE_ISO;
2218 /* FIXME: interface for non-ASAP data? */
2219 urb->flags = USBFS_URB_ISO_ASAP;
2220 urb->endpoint = transfer->endpoint;
2221 urb->number_of_packets = num_packets_in_urb;
2222 urb->buffer = urb_buffer;
2224 urb_buffer += urb->buffer_length;
2225 num_packets_remaining -= num_packets_in_urb;
2229 for (i = 0; i < num_urbs; i++) {
2230 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2232 if (errno == ENODEV) {
2233 r = LIBUSB_ERROR_NO_DEVICE;
2234 } else if (errno == EINVAL) {
2235 usbi_warn(TRANSFER_CTX(transfer),
2236 "submiturb failed, transfer too large");
2237 r = LIBUSB_ERROR_INVALID_PARAM;
2238 } else if (errno == EMSGSIZE) {
2239 usbi_warn(TRANSFER_CTX(transfer),
2240 "submiturb failed, iso packet length too large");
2241 r = LIBUSB_ERROR_INVALID_PARAM;
2243 usbi_err(TRANSFER_CTX(transfer),
2244 "submiturb failed, errno=%d", errno);
2245 r = LIBUSB_ERROR_IO;
2248 /* if the first URB submission fails, we can simply free up and
2249 * return failure immediately. */
2251 usbi_dbg("first URB failed, easy peasy");
2252 free_iso_urbs(tpriv);
2256 /* if it's not the first URB that failed, the situation is a bit
2257 * tricky. we must discard all previous URBs. there are
2259 * - discarding is asynchronous - discarded urbs will be reaped
2260 * later. the user must not have freed the transfer when the
2261 * discarded URBs are reaped, otherwise libusb will be using
2263 * - the earlier URBs may have completed successfully and we do
2264 * not want to throw away any data.
2265 * so, in this case we discard all the previous URBs BUT we report
2266 * that the transfer was submitted successfully. then later when
2267 * the final discard completes we can report error to the user.
2269 tpriv->reap_action = SUBMIT_FAILED;
2271 /* The URBs we haven't submitted yet we count as already
2273 tpriv->num_retired = num_urbs - i;
2274 discard_urbs(itransfer, 0, i);
2276 usbi_dbg("reporting successful submission but waiting for %d "
2277 "discards before reporting error", i);
2285 static int submit_control_transfer(struct usbi_transfer *itransfer)
2287 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2288 struct libusb_transfer *transfer =
2289 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2290 struct linux_device_handle_priv *dpriv =
2291 _device_handle_priv(transfer->dev_handle);
2292 struct usbfs_urb *urb;
2295 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2296 return LIBUSB_ERROR_INVALID_PARAM;
2298 urb = calloc(1, sizeof(struct usbfs_urb));
2300 return LIBUSB_ERROR_NO_MEM;
2302 tpriv->num_urbs = 1;
2303 tpriv->reap_action = NORMAL;
2305 urb->usercontext = itransfer;
2306 urb->type = USBFS_URB_TYPE_CONTROL;
2307 urb->endpoint = transfer->endpoint;
2308 urb->buffer = transfer->buffer;
2309 urb->buffer_length = transfer->length;
2311 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2315 if (errno == ENODEV)
2316 return LIBUSB_ERROR_NO_DEVICE;
2318 usbi_err(TRANSFER_CTX(transfer),
2319 "submiturb failed, errno=%d", errno);
2320 return LIBUSB_ERROR_IO;
2325 static int op_submit_transfer(struct usbi_transfer *itransfer)
2327 struct libusb_transfer *transfer =
2328 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2330 switch (transfer->type) {
2331 case LIBUSB_TRANSFER_TYPE_CONTROL:
2332 return submit_control_transfer(itransfer);
2333 case LIBUSB_TRANSFER_TYPE_BULK:
2334 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2335 return submit_bulk_transfer(itransfer);
2336 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2337 return submit_bulk_transfer(itransfer);
2338 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2339 return submit_iso_transfer(itransfer);
2341 usbi_err(TRANSFER_CTX(transfer),
2342 "unknown endpoint type %d", transfer->type);
2343 return LIBUSB_ERROR_INVALID_PARAM;
2347 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2349 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2350 struct libusb_transfer *transfer =
2351 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2355 return LIBUSB_ERROR_NOT_FOUND;
2357 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2361 switch (transfer->type) {
2362 case LIBUSB_TRANSFER_TYPE_BULK:
2363 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2364 if (tpriv->reap_action == ERROR)
2366 /* else, fall through */
2368 tpriv->reap_action = CANCELLED;
2374 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2376 struct libusb_transfer *transfer =
2377 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2378 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2380 switch (transfer->type) {
2381 case LIBUSB_TRANSFER_TYPE_CONTROL:
2382 case LIBUSB_TRANSFER_TYPE_BULK:
2383 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2384 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2390 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2391 if (tpriv->iso_urbs) {
2392 free_iso_urbs(tpriv);
2393 tpriv->iso_urbs = NULL;
2397 usbi_err(TRANSFER_CTX(transfer),
2398 "unknown endpoint type %d", transfer->type);
2402 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2403 struct usbfs_urb *urb)
2405 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2406 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2407 int urb_idx = urb - tpriv->urbs;
2409 usbi_mutex_lock(&itransfer->lock);
2410 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2411 urb_idx + 1, tpriv->num_urbs);
2413 tpriv->num_retired++;
2415 if (tpriv->reap_action != NORMAL) {
2416 /* cancelled, submit_fail, or completed early */
2417 usbi_dbg("abnormal reap: urb status %d", urb->status);
2419 /* even though we're in the process of cancelling, it's possible that
2420 * we may receive some data in these URBs that we don't want to lose.
2422 * 1. while the kernel is cancelling all the packets that make up an
2423 * URB, a few of them might complete. so we get back a successful
2424 * cancellation *and* some data.
2425 * 2. we receive a short URB which marks the early completion condition,
2426 * so we start cancelling the remaining URBs. however, we're too
2427 * slow and another URB completes (or at least completes partially).
2428 * (this can't happen since we always use BULK_CONTINUATION.)
2430 * When this happens, our objectives are not to lose any "surplus" data,
2431 * and also to stick it at the end of the previously-received data
2432 * (closing any holes), so that libusb reports the total amount of
2433 * transferred data and presents it in a contiguous chunk.
2435 if (urb->actual_length > 0) {
2436 unsigned char *target = transfer->buffer + itransfer->transferred;
2437 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2438 if (urb->buffer != target) {
2439 usbi_dbg("moving surplus data from offset %zd to offset %zd",
2440 (unsigned char *) urb->buffer - transfer->buffer,
2441 target - transfer->buffer);
2442 memmove(target, urb->buffer, urb->actual_length);
2444 itransfer->transferred += urb->actual_length;
2447 if (tpriv->num_retired == tpriv->num_urbs) {
2448 usbi_dbg("abnormal reap: last URB handled, reporting");
2449 if (tpriv->reap_action != COMPLETED_EARLY &&
2450 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2451 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2457 itransfer->transferred += urb->actual_length;
2459 /* Many of these errors can occur on *any* urb of a multi-urb
2460 * transfer. When they do, we tear down the rest of the transfer.
2462 switch (urb->status) {
2465 case -EREMOTEIO: /* short transfer */
2467 case -ENOENT: /* cancelled */
2472 usbi_dbg("device removed");
2473 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2474 goto cancel_remaining;
2476 usbi_dbg("detected endpoint stall");
2477 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2478 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2479 goto cancel_remaining;
2481 /* overflow can only ever occur in the last urb */
2482 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2483 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2484 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2491 usbi_dbg("low level error %d", urb->status);
2492 tpriv->reap_action = ERROR;
2493 goto cancel_remaining;
2495 usbi_warn(ITRANSFER_CTX(itransfer),
2496 "unrecognised urb status %d", urb->status);
2497 tpriv->reap_action = ERROR;
2498 goto cancel_remaining;
2501 /* if we've reaped all urbs or we got less data than requested then we're
2503 if (tpriv->num_retired == tpriv->num_urbs) {
2504 usbi_dbg("all URBs in transfer reaped --> complete!");
2506 } else if (urb->actual_length < urb->buffer_length) {
2507 usbi_dbg("short transfer %d/%d --> complete!",
2508 urb->actual_length, urb->buffer_length);
2509 if (tpriv->reap_action == NORMAL)
2510 tpriv->reap_action = COMPLETED_EARLY;
2515 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2516 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2518 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2521 /* cancel remaining urbs and wait for their completion before
2522 * reporting results */
2523 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2526 usbi_mutex_unlock(&itransfer->lock);
2532 usbi_mutex_unlock(&itransfer->lock);
2533 return CANCELLED == tpriv->reap_action ?
2534 usbi_handle_transfer_cancellation(itransfer) :
2535 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2538 static int handle_iso_completion(struct usbi_transfer *itransfer,
2539 struct usbfs_urb *urb)
2541 struct libusb_transfer *transfer =
2542 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2543 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2544 int num_urbs = tpriv->num_urbs;
2547 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2549 usbi_mutex_lock(&itransfer->lock);
2550 for (i = 0; i < num_urbs; i++) {
2551 if (urb == tpriv->iso_urbs[i]) {
2557 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2558 usbi_mutex_unlock(&itransfer->lock);
2559 return LIBUSB_ERROR_NOT_FOUND;
2562 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2565 /* copy isochronous results back in */
2567 for (i = 0; i < urb->number_of_packets; i++) {
2568 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2569 struct libusb_iso_packet_descriptor *lib_desc =
2570 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2571 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2572 switch (urb_desc->status) {
2575 case -ENOENT: /* cancelled */
2580 usbi_dbg("packet %d - device removed", i);
2581 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2584 usbi_dbg("packet %d - detected endpoint stall", i);
2585 lib_desc->status = LIBUSB_TRANSFER_STALL;
2588 usbi_dbg("packet %d - overflow error", i);
2589 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2597 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2598 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2601 usbi_warn(TRANSFER_CTX(transfer),
2602 "packet %d - unrecognised urb status %d", i, urb_desc->status);
2603 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2606 lib_desc->actual_length = urb_desc->actual_length;
2609 tpriv->num_retired++;
2611 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2612 usbi_dbg("CANCEL: urb status %d", urb->status);
2614 if (tpriv->num_retired == num_urbs) {
2615 usbi_dbg("CANCEL: last URB handled, reporting");
2616 free_iso_urbs(tpriv);
2617 if (tpriv->reap_action == CANCELLED) {
2618 usbi_mutex_unlock(&itransfer->lock);
2619 return usbi_handle_transfer_cancellation(itransfer);
2621 usbi_mutex_unlock(&itransfer->lock);
2622 return usbi_handle_transfer_completion(itransfer,
2623 LIBUSB_TRANSFER_ERROR);
2629 switch (urb->status) {
2632 case -ENOENT: /* cancelled */
2636 usbi_dbg("device removed");
2637 status = LIBUSB_TRANSFER_NO_DEVICE;
2640 usbi_warn(TRANSFER_CTX(transfer),
2641 "unrecognised urb status %d", urb->status);
2642 status = LIBUSB_TRANSFER_ERROR;
2646 /* if we've reaped all urbs then we're done */
2647 if (tpriv->num_retired == num_urbs) {
2648 usbi_dbg("all URBs in transfer reaped --> complete!");
2649 free_iso_urbs(tpriv);
2650 usbi_mutex_unlock(&itransfer->lock);
2651 return usbi_handle_transfer_completion(itransfer, status);
2655 usbi_mutex_unlock(&itransfer->lock);
2659 static int handle_control_completion(struct usbi_transfer *itransfer,
2660 struct usbfs_urb *urb)
2662 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2665 usbi_mutex_lock(&itransfer->lock);
2666 usbi_dbg("handling completion status %d", urb->status);
2668 itransfer->transferred += urb->actual_length;
2670 if (tpriv->reap_action == CANCELLED) {
2671 if (urb->status != 0 && urb->status != -ENOENT)
2672 usbi_warn(ITRANSFER_CTX(itransfer),
2673 "cancel: unrecognised urb status %d", urb->status);
2676 usbi_mutex_unlock(&itransfer->lock);
2677 return usbi_handle_transfer_cancellation(itransfer);
2680 switch (urb->status) {
2682 status = LIBUSB_TRANSFER_COMPLETED;
2684 case -ENOENT: /* cancelled */
2685 status = LIBUSB_TRANSFER_CANCELLED;
2689 usbi_dbg("device removed");
2690 status = LIBUSB_TRANSFER_NO_DEVICE;
2693 usbi_dbg("unsupported control request");
2694 status = LIBUSB_TRANSFER_STALL;
2697 usbi_dbg("control overflow error");
2698 status = LIBUSB_TRANSFER_OVERFLOW;
2705 usbi_dbg("low-level bus error occurred");
2706 status = LIBUSB_TRANSFER_ERROR;
2709 usbi_warn(ITRANSFER_CTX(itransfer),
2710 "unrecognised urb status %d", urb->status);
2711 status = LIBUSB_TRANSFER_ERROR;
2717 usbi_mutex_unlock(&itransfer->lock);
2718 return usbi_handle_transfer_completion(itransfer, status);
2721 static int reap_for_handle(struct libusb_device_handle *handle)
2723 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2725 struct usbfs_urb *urb = NULL;
2726 struct usbi_transfer *itransfer;
2727 struct libusb_transfer *transfer;
2729 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2730 if (r == -1 && errno == EAGAIN)
2733 if (errno == ENODEV)
2734 return LIBUSB_ERROR_NO_DEVICE;
2736 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2737 return LIBUSB_ERROR_IO;
2740 itransfer = urb->usercontext;
2741 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2743 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2744 urb->actual_length);
2746 switch (transfer->type) {
2747 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2748 return handle_iso_completion(itransfer, urb);
2749 case LIBUSB_TRANSFER_TYPE_BULK:
2750 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2751 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2752 return handle_bulk_completion(itransfer, urb);
2753 case LIBUSB_TRANSFER_TYPE_CONTROL:
2754 return handle_control_completion(itransfer, urb);
2756 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2758 return LIBUSB_ERROR_OTHER;
2762 static int op_handle_events(struct libusb_context *ctx,
2763 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2768 usbi_mutex_lock(&ctx->open_devs_lock);
2769 for (i = 0; i < nfds && num_ready > 0; i++) {
2770 struct pollfd *pollfd = &fds[i];
2771 struct libusb_device_handle *handle;
2772 struct linux_device_handle_priv *hpriv = NULL;
2774 if (!pollfd->revents)
2778 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2779 hpriv = _device_handle_priv(handle);
2780 if (hpriv->fd == pollfd->fd)
2784 if (!hpriv || hpriv->fd != pollfd->fd) {
2785 usbi_err(ctx, "cannot find handle for fd %d",
2790 if (pollfd->revents & POLLERR) {
2791 /* remove the fd from the pollfd set so that it doesn't continuously
2792 * trigger an event, and flag that it has been removed so op_close()
2793 * doesn't try to remove it a second time */
2794 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2795 hpriv->fd_removed = 1;
2797 /* device will still be marked as attached if hotplug monitor thread
2798 * hasn't processed remove event yet */
2799 usbi_mutex_static_lock(&linux_hotplug_lock);
2800 if (handle->dev->attached)
2801 linux_device_disconnected(handle->dev->bus_number,
2802 handle->dev->device_address);
2803 usbi_mutex_static_unlock(&linux_hotplug_lock);
2805 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2807 r = reap_for_handle(handle);
2811 usbi_handle_disconnect(handle);
2816 r = reap_for_handle(handle);
2818 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2826 usbi_mutex_unlock(&ctx->open_devs_lock);
2830 static int op_clock_gettime(int clk_id, struct timespec *tp)
2833 case USBI_CLOCK_MONOTONIC:
2834 return clock_gettime(monotonic_clkid, tp);
2835 case USBI_CLOCK_REALTIME:
2836 return clock_gettime(CLOCK_REALTIME, tp);
2838 return LIBUSB_ERROR_INVALID_PARAM;
2842 #ifdef USBI_TIMERFD_AVAILABLE
2843 static clockid_t op_get_timerfd_clockid(void)
2845 return monotonic_clkid;
2850 const struct usbi_os_backend usbi_backend = {
2851 .name = "Linux usbfs",
2852 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2855 .hotplug_poll = op_hotplug_poll,
2856 .get_device_descriptor = op_get_device_descriptor,
2857 .get_active_config_descriptor = op_get_active_config_descriptor,
2858 .get_config_descriptor = op_get_config_descriptor,
2859 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2861 .wrap_sys_device = op_wrap_sys_device,
2864 .get_configuration = op_get_configuration,
2865 .set_configuration = op_set_configuration,
2866 .claim_interface = op_claim_interface,
2867 .release_interface = op_release_interface,
2869 .set_interface_altsetting = op_set_interface,
2870 .clear_halt = op_clear_halt,
2871 .reset_device = op_reset_device,
2873 .alloc_streams = op_alloc_streams,
2874 .free_streams = op_free_streams,
2876 .dev_mem_alloc = op_dev_mem_alloc,
2877 .dev_mem_free = op_dev_mem_free,
2879 .kernel_driver_active = op_kernel_driver_active,
2880 .detach_kernel_driver = op_detach_kernel_driver,
2881 .attach_kernel_driver = op_attach_kernel_driver,
2883 .destroy_device = op_destroy_device,
2885 .submit_transfer = op_submit_transfer,
2886 .cancel_transfer = op_cancel_transfer,
2887 .clear_transfer_priv = op_clear_transfer_priv,
2889 .handle_events = op_handle_events,
2891 .clock_gettime = op_clock_gettime,
2893 #ifdef USBI_TIMERFD_AVAILABLE
2894 .get_timerfd_clockid = op_get_timerfd_clockid,
2897 .device_priv_size = sizeof(struct linux_device_priv),
2898 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2899 .transfer_priv_size = sizeof(struct linux_transfer_priv),