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 #ifdef USE_USBHOST_API
44 #include <dbus/dbus.h>
48 #include "linux_usbfs.h"
51 * opening a usbfs node causes the device to be resumed, so we attempt to
52 * avoid this during enumeration.
54 * sysfs allows us to read the kernel's in-memory copies of device descriptors
55 * and so forth, avoiding the need to open the device:
56 * - The binary "descriptors" file contains all config descriptors since
57 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
58 * - The binary "descriptors" file was added in 2.6.23, commit
59 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
60 * active config descriptors
61 * - The "busnum" file was added in 2.6.22, commit
62 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
63 * - The "devnum" file has been present since pre-2.6.18
64 * - the "bConfigurationValue" file has been present since pre-2.6.18
66 * If we have bConfigurationValue, busnum, and devnum, then we can determine
67 * the active configuration without having to open the usbfs node in RDWR mode.
68 * The busnum file is important as that is the only way we can relate sysfs
69 * devices to usbfs nodes.
71 * If we also have all descriptors, we can obtain the device descriptor and
72 * configuration without touching usbfs at all.
75 /* endianness for multi-byte fields:
77 * Descriptors exposed by usbfs have the multi-byte fields in the device
78 * descriptor as host endian. Multi-byte fields in the other descriptors are
79 * bus-endian. The kernel documentation says otherwise, but it is wrong.
81 * In sysfs all descriptors are bus-endian.
84 static const char *usbfs_path = NULL;
86 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
87 static int usbdev_names = 0;
89 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
90 * allows us to mark URBs as being part of a specific logical transfer when
91 * we submit them to the kernel. then, on any error except a cancellation, all
92 * URBs within that transfer will be cancelled and no more URBs will be
93 * accepted for the transfer, meaning that no more data can creep in.
95 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
96 * (in either direction) except the first.
97 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
98 * last; it means that the kernel should treat a short reply as an error.
99 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
100 * transfers can't be short unless there's already some sort of error), and
101 * setting this flag is disallowed (a kernel with USB debugging enabled will
104 static int supports_flag_bulk_continuation = -1;
106 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
107 * allows us to mark URBs that should be followed by a zero length data
108 * packet, which can be required by device- or class-specific protocols.
110 static int supports_flag_zero_packet = -1;
112 /* clock ID for monotonic clock, as not all clock sources are available on all
113 * systems. appropriate choice made at initialization time. */
114 static clockid_t monotonic_clkid = -1;
116 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
117 * to sysfs, so we can relate devices. This also implies that we can read
118 * the active configuration through bConfigurationValue */
119 static int sysfs_can_relate_devices = -1;
121 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
122 * config descriptors (rather then just the active config) to the sysfs
123 * descriptors file, so from then on we can use them. */
124 static int sysfs_has_descriptors = -1;
126 /* how many times have we initted (and not exited) ? */
127 static int init_count = 0;
129 /* Serialize hotplug start/stop */
130 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
131 /* Serialize scan-devices, event-thread, and poll */
132 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
134 static int linux_start_event_monitor(void);
135 static int linux_stop_event_monitor(void);
136 static int linux_scan_devices(struct libusb_context *ctx);
137 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
138 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
140 #if !defined(USE_UDEV)
141 static int linux_default_scan_devices (struct libusb_context *ctx);
144 struct linux_device_priv {
146 unsigned char *descriptors;
148 int active_config; /* cache val for !sysfs_can_relate_devices */
151 struct linux_device_handle_priv {
159 /* submission failed after the first URB, so await cancellation/completion
160 * of all the others */
163 /* cancelled by user or timeout */
166 /* completed multi-URB transfer in non-final URB */
169 /* one or more urbs encountered a low-level error */
173 struct linux_transfer_priv {
175 struct usbfs_urb *urbs;
176 struct usbfs_urb **iso_urbs;
179 enum reap_action reap_action;
182 enum libusb_transfer_status reap_status;
184 /* next iso packet in user-supplied transfer to be populated */
185 int iso_packet_offset;
188 static int _direct_open_device(struct libusb_context *ctx, const char *path,
189 mode_t mode, int silent)
194 fd = open(path, mode);
196 return fd; /* Success */
198 if (errno == ENOENT) {
200 usbi_err(ctx, "File doesn't exist,"
201 "wait %d ms and try again\n", delay/1000);
203 /* Wait 10ms for USB device path creation.*/
206 fd = open(path, mode);
208 return fd; /* Success */
214 #ifdef USE_USBHOST_API
216 #define DEVICED_BUS_NAME "org.tizen.system.deviced"
217 #define DEVICED_OBJECT_PATH "/Org/Tizen/System/DeviceD"
218 #define DEVICED_INTERFACE_NAME DEVICED_BUS_NAME
219 #define DEVICED_PATH_USBHOST DEVICED_OBJECT_PATH"/Usbhost"
220 #define DEVICED_INTERFACE_USBHOST DEVICED_INTERFACE_NAME".Usbhost"
221 #define METHOD_OPEN_DEVICE "OpenDevice"
223 DBusMessage *dbus_method_sync_with_reply(const char *dest, const char *path,
224 const char *interface, const char *method, const char *param)
226 DBusConnection *conn;
228 DBusMessageIter iter;
232 conn = dbus_bus_get(DBUS_BUS_SYSTEM, NULL);
234 usbi_err(NULL, "dbus_bus_get error");
238 msg = dbus_message_new_method_call(dest, path, interface, method);
240 usbi_err(NULL, "dbus_message_new_method_call(%s:%s-%s)",
241 path, interface, method);
242 dbus_connection_unref (conn);
246 dbus_message_iter_init_append(msg, &iter);
247 dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, ¶m);
249 dbus_error_init(&err);
251 reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
253 usbi_err(NULL, "dbus_connection_send error(No reply) %s %s:%s-%s",
254 dest, path, interface, method);
257 if (dbus_error_is_set(&err)) {
258 usbi_err(NULL, "dbus_connection_send error(%s:%s) %s %s:%s-%s",
259 err.name, err.message, dest, path, interface, method);
260 dbus_error_free(&err);
264 dbus_message_unref(msg);
265 dbus_connection_unref (conn);
269 static int open_usb_device(const char *path, int *fd)
279 dbus_error_init(&err);
281 reply = dbus_method_sync_with_reply(DEVICED_BUS_NAME,
282 DEVICED_PATH_USBHOST,
283 DEVICED_INTERFACE_USBHOST,
288 usbi_err(NULL, "Unable to open USB device");
292 result = dbus_message_get_args(reply, &err,
293 DBUS_TYPE_INT32, &ret,
294 DBUS_TYPE_UNIX_FD, &rfd,
297 usbi_err(NULL, "Failed to get arguments: %s", err.message);
307 static int _ask_for_open(const char *path, mode_t mode, int silent)
312 ret = open_usb_device(path, &fd);
315 * We have an error so let's set errno correctly
316 * just like open does
326 #endif /* USE_USBHOST_API */
328 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
330 struct libusb_context *ctx = DEVICE_CTX(dev);
335 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
336 usbfs_path, dev->bus_number, dev->device_address);
338 snprintf(path, PATH_MAX, "%s/%03d/%03d",
339 usbfs_path, dev->bus_number, dev->device_address);
341 fd = _direct_open_device(ctx, path, mode, silent);
343 return fd; /* Success */
345 #ifdef USE_USBHOST_API
347 * If we are here, we were unable to go simple
348 * path and open the device directly. In Tizen
349 * we have USB security daemon (USD) which
350 * manages access rights to USB device nodes.
351 * Now let's ask him to open this device node
356 * USD is applicable only for RW access.
360 usbi_info(ctx, "No direct access to device node: %s. "
361 "Trying to use deviced", path);
363 fd = _ask_for_open(path, mode, silent);
367 #endif /* USE_USBHOST_API */
370 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
371 path, strerror(errno));
372 if (errno == EACCES && mode == O_RDWR)
373 usbi_err(ctx, "libusb requires write access to USB "
378 return LIBUSB_ERROR_ACCESS;
380 return LIBUSB_ERROR_NO_DEVICE;
381 return LIBUSB_ERROR_IO;
384 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
386 return (struct linux_device_priv *) dev->os_priv;
389 static struct linux_device_handle_priv *_device_handle_priv(
390 struct libusb_device_handle *handle)
392 return (struct linux_device_handle_priv *) handle->os_priv;
395 /* check dirent for a /dev/usbdev%d.%d name
396 * optionally return bus/device on success */
397 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
401 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
404 usbi_dbg("found: %s", entry->d_name);
412 static int check_usb_vfs(const char *dirname)
415 struct dirent *entry;
418 dir = opendir(dirname);
422 while ((entry = readdir(dir)) != NULL) {
423 if (entry->d_name[0] == '.')
426 /* We assume if we find any files that it must be the right place */
435 static const char *find_usbfs_path(void)
437 const char *path = "/dev/bus/usb";
438 const char *ret = NULL;
440 if (check_usb_vfs(path)) {
443 path = "/proc/bus/usb";
444 if (check_usb_vfs(path))
448 /* look for /dev/usbdev*.* if the normal places fail */
450 struct dirent *entry;
456 while ((entry = readdir(dir)) != NULL) {
457 if (_is_usbdev_entry(entry, NULL, NULL)) {
458 /* found one; that's enough */
468 /* On udev based systems without any usb-devices /dev/bus/usb will not
469 * exist. So if we've not found anything and we're using udev for hotplug
470 * simply assume /dev/bus/usb rather then making libusb_init fail. */
471 #if defined(USE_UDEV)
473 ret = "/dev/bus/usb";
477 usbi_dbg("found usbfs at %s", ret);
482 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
483 * seem to lack it). fall back to REALTIME if we have to. */
484 static clockid_t find_monotonic_clock(void)
486 #ifdef CLOCK_MONOTONIC
490 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
491 * because it's not available through timerfd */
492 r = clock_gettime(CLOCK_MONOTONIC, &ts);
494 return CLOCK_MONOTONIC;
495 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
498 return CLOCK_REALTIME;
501 static int kernel_version_ge(int major, int minor, int sublevel)
504 int atoms, kmajor, kminor, ksublevel;
508 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
517 /* kmajor == major */
519 return 0 == minor && 0 == sublevel;
525 /* kminor == minor */
527 return 0 == sublevel;
529 return ksublevel >= sublevel;
532 static int op_init(struct libusb_context *ctx)
537 usbfs_path = find_usbfs_path();
539 usbi_err(ctx, "could not find usbfs");
540 return LIBUSB_ERROR_OTHER;
543 if (monotonic_clkid == -1)
544 monotonic_clkid = find_monotonic_clock();
546 if (supports_flag_bulk_continuation == -1) {
547 /* bulk continuation URB flag available from Linux 2.6.32 */
548 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
549 if (supports_flag_bulk_continuation == -1) {
550 usbi_err(ctx, "error checking for bulk continuation support");
551 return LIBUSB_ERROR_OTHER;
555 if (supports_flag_bulk_continuation)
556 usbi_dbg("bulk continuation flag supported");
558 if (-1 == supports_flag_zero_packet) {
559 /* zero length packet URB flag fixed since Linux 2.6.31 */
560 supports_flag_zero_packet = kernel_version_ge(2,6,31);
561 if (-1 == supports_flag_zero_packet) {
562 usbi_err(ctx, "error checking for zero length packet support");
563 return LIBUSB_ERROR_OTHER;
567 if (supports_flag_zero_packet)
568 usbi_dbg("zero length packet flag supported");
570 if (-1 == sysfs_has_descriptors) {
571 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
572 sysfs_has_descriptors = kernel_version_ge(2,6,26);
573 if (-1 == sysfs_has_descriptors) {
574 usbi_err(ctx, "error checking for sysfs descriptors");
575 return LIBUSB_ERROR_OTHER;
579 if (-1 == sysfs_can_relate_devices) {
580 /* sysfs has busnum since Linux 2.6.22 */
581 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
582 if (-1 == sysfs_can_relate_devices) {
583 usbi_err(ctx, "error checking for sysfs busnum");
584 return LIBUSB_ERROR_OTHER;
588 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
589 r = stat(SYSFS_DEVICE_PATH, &statbuf);
590 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
591 usbi_warn(ctx, "sysfs not mounted");
592 sysfs_can_relate_devices = 0;
593 sysfs_has_descriptors = 0;
597 if (sysfs_can_relate_devices)
598 usbi_dbg("sysfs can relate devices");
600 if (sysfs_has_descriptors)
601 usbi_dbg("sysfs has complete descriptors");
603 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
605 if (init_count == 0) {
606 /* start up hotplug event handler */
607 r = linux_start_event_monitor();
609 if (r == LIBUSB_SUCCESS) {
610 r = linux_scan_devices(ctx);
611 if (r == LIBUSB_SUCCESS)
613 else if (init_count == 0)
614 linux_stop_event_monitor();
616 usbi_err(ctx, "error starting hotplug event monitor");
617 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
622 static void op_exit(void)
624 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
625 assert(init_count != 0);
627 /* tear down event handler */
628 (void)linux_stop_event_monitor();
630 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
633 static int linux_start_event_monitor(void)
635 #if defined(USE_UDEV)
636 return linux_udev_start_event_monitor();
638 return linux_netlink_start_event_monitor();
642 static int linux_stop_event_monitor(void)
644 #if defined(USE_UDEV)
645 return linux_udev_stop_event_monitor();
647 return linux_netlink_stop_event_monitor();
651 static int linux_scan_devices(struct libusb_context *ctx)
655 usbi_mutex_static_lock(&linux_hotplug_lock);
657 #if defined(USE_UDEV)
658 ret = linux_udev_scan_devices(ctx);
660 ret = linux_default_scan_devices(ctx);
663 usbi_mutex_static_unlock(&linux_hotplug_lock);
668 static void op_hotplug_poll(void)
670 #if defined(USE_UDEV)
671 linux_udev_hotplug_poll();
673 linux_netlink_hotplug_poll();
677 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
679 struct linux_device_priv *priv = _device_priv(dev);
680 char filename[PATH_MAX];
683 snprintf(filename, PATH_MAX, "%s/%s/%s",
684 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
685 fd = open(filename, O_RDONLY);
687 usbi_err(DEVICE_CTX(dev),
688 "open %s failed ret=%d errno=%d", filename, fd, errno);
689 return LIBUSB_ERROR_IO;
695 /* Note only suitable for attributes which always read >= 0, < 0 is error */
696 static int __read_sysfs_attr(struct libusb_context *ctx,
697 const char *devname, const char *attr)
699 char filename[PATH_MAX];
703 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
705 f = fopen(filename, "r");
707 if (errno == ENOENT) {
708 /* File doesn't exist. Assume the device has been
709 disconnected (see trac ticket #70). */
710 return LIBUSB_ERROR_NO_DEVICE;
712 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
713 return LIBUSB_ERROR_IO;
716 r = fscanf(f, "%d", &value);
719 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
720 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
723 usbi_err(ctx, "%s contains a negative value", filename);
724 return LIBUSB_ERROR_IO;
730 static int op_get_device_descriptor(struct libusb_device *dev,
731 unsigned char *buffer, int *host_endian)
733 struct linux_device_priv *priv = _device_priv(dev);
735 *host_endian = sysfs_has_descriptors ? 0 : 1;
736 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
741 /* read the bConfigurationValue for a device */
742 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
745 char tmp[5] = {0, 0, 0, 0, 0};
750 fd = _open_sysfs_attr(dev, "bConfigurationValue");
754 r = read(fd, tmp, sizeof(tmp));
757 usbi_err(DEVICE_CTX(dev),
758 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
759 return LIBUSB_ERROR_IO;
761 usbi_dbg("device unconfigured");
766 if (tmp[sizeof(tmp) - 1] != 0) {
767 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
768 return LIBUSB_ERROR_IO;
769 } else if (tmp[0] == 0) {
770 usbi_err(DEVICE_CTX(dev), "no configuration value?");
771 return LIBUSB_ERROR_IO;
774 num = strtol(tmp, &endptr, 10);
776 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
777 return LIBUSB_ERROR_IO;
784 int linux_get_device_address (struct libusb_context *ctx, int detached,
785 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
786 const char *sys_name)
790 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
791 /* can't use sysfs to read the bus and device number if the
792 * device has been detached */
793 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
794 if (NULL == dev_node) {
795 return LIBUSB_ERROR_OTHER;
798 /* will this work with all supported kernel versions? */
799 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
800 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
801 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
802 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
805 return LIBUSB_SUCCESS;
808 usbi_dbg("scan %s", sys_name);
810 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
813 if (sysfs_attr > 255)
814 return LIBUSB_ERROR_INVALID_PARAM;
815 *busnum = (uint8_t) sysfs_attr;
817 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
820 if (sysfs_attr > 255)
821 return LIBUSB_ERROR_INVALID_PARAM;
823 *devaddr = (uint8_t) sysfs_attr;
825 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
827 return LIBUSB_SUCCESS;
830 /* Return offset of the next descriptor with the given type */
831 static int seek_to_next_descriptor(struct libusb_context *ctx,
832 uint8_t descriptor_type, unsigned char *buffer, int size)
834 struct usb_descriptor_header header;
837 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
839 return LIBUSB_ERROR_NOT_FOUND;
842 usbi_err(ctx, "short descriptor read %d/2", size);
843 return LIBUSB_ERROR_IO;
845 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
847 if (i && header.bDescriptorType == descriptor_type)
850 usbi_err(ctx, "bLength overflow by %d bytes", -size);
851 return LIBUSB_ERROR_IO;
854 /* Return offset to next config */
855 static int seek_to_next_config(struct libusb_context *ctx,
856 unsigned char *buffer, int size)
858 struct libusb_config_descriptor config;
861 return LIBUSB_ERROR_NOT_FOUND;
863 if (size < LIBUSB_DT_CONFIG_SIZE) {
864 usbi_err(ctx, "short descriptor read %d/%d",
865 size, LIBUSB_DT_CONFIG_SIZE);
866 return LIBUSB_ERROR_IO;
869 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
870 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
871 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
872 config.bDescriptorType);
873 return LIBUSB_ERROR_IO;
877 * In usbfs the config descriptors are config.wTotalLength bytes apart,
878 * with any short reads from the device appearing as holes in the file.
880 * In sysfs wTotalLength is ignored, instead the kernel returns a
881 * config descriptor with verified bLength fields, with descriptors
882 * with an invalid bLength removed.
884 if (sysfs_has_descriptors) {
885 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
887 if (next == LIBUSB_ERROR_NOT_FOUND)
892 if (next != config.wTotalLength)
893 usbi_warn(ctx, "config length mismatch wTotalLength "
894 "%d real %d", config.wTotalLength, next);
897 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
898 usbi_err(ctx, "invalid wTotalLength %d",
899 config.wTotalLength);
900 return LIBUSB_ERROR_IO;
901 } else if (config.wTotalLength > size) {
902 usbi_warn(ctx, "short descriptor read %d/%d",
903 size, config.wTotalLength);
906 return config.wTotalLength;
910 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
911 uint8_t value, unsigned char **buffer, int *host_endian)
913 struct libusb_context *ctx = DEVICE_CTX(dev);
914 struct linux_device_priv *priv = _device_priv(dev);
915 unsigned char *descriptors = priv->descriptors;
916 int size = priv->descriptors_len;
917 struct libusb_config_descriptor *config;
920 /* Unlike the device desc. config descs. are always in raw format */
923 /* Skip device header */
924 descriptors += DEVICE_DESC_LENGTH;
925 size -= DEVICE_DESC_LENGTH;
927 /* Seek till the config is found, or till "EOF" */
929 int next = seek_to_next_config(ctx, descriptors, size);
932 config = (struct libusb_config_descriptor *)descriptors;
933 if (config->bConfigurationValue == value) {
934 *buffer = descriptors;
942 static int op_get_active_config_descriptor(struct libusb_device *dev,
943 unsigned char *buffer, size_t len, int *host_endian)
946 unsigned char *config_desc;
948 if (sysfs_can_relate_devices) {
949 r = sysfs_get_active_config(dev, &config);
953 /* Use cached bConfigurationValue */
954 struct linux_device_priv *priv = _device_priv(dev);
955 config = priv->active_config;
958 return LIBUSB_ERROR_NOT_FOUND;
960 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
966 memcpy(buffer, config_desc, len);
970 static int op_get_config_descriptor(struct libusb_device *dev,
971 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
973 struct linux_device_priv *priv = _device_priv(dev);
974 unsigned char *descriptors = priv->descriptors;
975 int i, r, size = priv->descriptors_len;
977 /* Unlike the device desc. config descs. are always in raw format */
980 /* Skip device header */
981 descriptors += DEVICE_DESC_LENGTH;
982 size -= DEVICE_DESC_LENGTH;
984 /* Seek till the config is found, or till "EOF" */
986 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
989 if (i == config_index)
996 memcpy(buffer, descriptors, len);
1000 /* send a control message to retrieve active configuration */
1001 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
1003 struct linux_device_priv *priv = _device_priv(dev);
1004 unsigned char active_config = 0;
1007 struct usbfs_ctrltransfer ctrl = {
1008 .bmRequestType = LIBUSB_ENDPOINT_IN,
1009 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
1014 .data = &active_config
1017 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
1019 if (errno == ENODEV)
1020 return LIBUSB_ERROR_NO_DEVICE;
1022 /* we hit this error path frequently with buggy devices :( */
1023 usbi_warn(DEVICE_CTX(dev),
1024 "get_configuration failed ret=%d errno=%d", r, errno);
1025 priv->active_config = -1;
1027 if (active_config > 0) {
1028 priv->active_config = active_config;
1030 /* some buggy devices have a configuration 0, but we're
1031 * reaching into the corner of a corner case here, so let's
1032 * not support buggy devices in these circumstances.
1033 * stick to the specs: a configuration value of 0 means
1035 usbi_warn(DEVICE_CTX(dev),
1036 "active cfg 0? assuming unconfigured device");
1037 priv->active_config = -1;
1041 return LIBUSB_SUCCESS;
1044 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
1045 uint8_t devaddr, const char *sysfs_dir)
1047 struct linux_device_priv *priv = _device_priv(dev);
1048 struct libusb_context *ctx = DEVICE_CTX(dev);
1049 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
1053 dev->bus_number = busnum;
1054 dev->device_address = devaddr;
1057 priv->sysfs_dir = strdup(sysfs_dir);
1058 if (!priv->sysfs_dir)
1059 return LIBUSB_ERROR_NO_MEM;
1061 /* Note speed can contain 1.5, in this case __read_sysfs_attr
1062 will stop parsing at the '.' and return 1 */
1063 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
1066 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
1067 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
1068 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
1069 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
1071 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
1076 /* cache descriptors in memory */
1077 if (sysfs_has_descriptors)
1078 fd = _open_sysfs_attr(dev, "descriptors");
1080 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1085 descriptors_size *= 2;
1086 priv->descriptors = usbi_reallocf(priv->descriptors,
1088 if (!priv->descriptors) {
1090 return LIBUSB_ERROR_NO_MEM;
1092 /* usbfs has holes in the file */
1093 if (!sysfs_has_descriptors) {
1094 memset(priv->descriptors + priv->descriptors_len,
1095 0, descriptors_size - priv->descriptors_len);
1097 r = read(fd, priv->descriptors + priv->descriptors_len,
1098 descriptors_size - priv->descriptors_len);
1100 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1103 return LIBUSB_ERROR_IO;
1105 priv->descriptors_len += r;
1106 } while (priv->descriptors_len == descriptors_size);
1110 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1111 usbi_err(ctx, "short descriptor read (%d)",
1112 priv->descriptors_len);
1113 return LIBUSB_ERROR_IO;
1116 if (sysfs_can_relate_devices)
1117 return LIBUSB_SUCCESS;
1119 /* cache active config */
1120 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1122 /* cannot send a control message to determine the active
1123 * config. just assume the first one is active. */
1124 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1125 "active configuration descriptor");
1126 if (priv->descriptors_len >=
1127 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1128 struct libusb_config_descriptor config;
1129 usbi_parse_descriptor(
1130 priv->descriptors + DEVICE_DESC_LENGTH,
1131 "bbwbbbbb", &config, 0);
1132 priv->active_config = config.bConfigurationValue;
1134 priv->active_config = -1; /* No config dt */
1136 return LIBUSB_SUCCESS;
1139 r = usbfs_get_active_config(dev, fd);
1145 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1147 struct libusb_context *ctx = DEVICE_CTX(dev);
1148 struct libusb_device *it;
1149 char *parent_sysfs_dir, *tmp;
1150 int ret, add_parent = 1;
1152 /* XXX -- can we figure out the topology when using usbfs? */
1153 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1154 /* either using usbfs or finding the parent of a root hub */
1155 return LIBUSB_SUCCESS;
1158 parent_sysfs_dir = strdup(sysfs_dir);
1159 if (NULL == parent_sysfs_dir) {
1160 return LIBUSB_ERROR_NO_MEM;
1162 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1163 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1164 dev->port_number = atoi(tmp + 1);
1167 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1169 free (parent_sysfs_dir);
1170 return LIBUSB_SUCCESS;
1173 /* is the parent a root hub? */
1174 if (NULL == strchr(parent_sysfs_dir, '-')) {
1175 tmp = parent_sysfs_dir;
1176 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1179 return LIBUSB_ERROR_NO_MEM;
1184 /* find the parent in the context */
1185 usbi_mutex_lock(&ctx->usb_devs_lock);
1186 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1187 struct linux_device_priv *priv = _device_priv(it);
1188 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1189 dev->parent_dev = libusb_ref_device(it);
1193 usbi_mutex_unlock(&ctx->usb_devs_lock);
1195 if (!dev->parent_dev && add_parent) {
1196 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1198 sysfs_scan_device(ctx, parent_sysfs_dir);
1203 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1204 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1206 free (parent_sysfs_dir);
1208 return LIBUSB_SUCCESS;
1211 int linux_enumerate_device(struct libusb_context *ctx,
1212 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1214 unsigned long session_id;
1215 struct libusb_device *dev;
1218 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1219 * will be reused. instead we should add a simple sysfs attribute with
1221 session_id = busnum << 8 | devaddr;
1222 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1225 dev = usbi_get_device_by_session_id(ctx, session_id);
1227 /* device already exists in the context */
1228 usbi_dbg("session_id %ld already exists", session_id);
1229 libusb_unref_device(dev);
1230 return LIBUSB_SUCCESS;
1233 usbi_dbg("allocating new device for %d/%d (session %ld)",
1234 busnum, devaddr, session_id);
1235 dev = usbi_alloc_device(ctx, session_id);
1237 return LIBUSB_ERROR_NO_MEM;
1239 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1242 r = usbi_sanitize_device(dev);
1246 r = linux_get_parent_info(dev, sysfs_dir);
1251 libusb_unref_device(dev);
1253 usbi_connect_device(dev);
1258 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1260 struct libusb_context *ctx;
1262 usbi_mutex_static_lock(&active_contexts_lock);
1263 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1264 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1266 usbi_mutex_static_unlock(&active_contexts_lock);
1269 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1271 struct libusb_context *ctx;
1272 struct libusb_device *dev;
1273 unsigned long session_id = busnum << 8 | devaddr;
1275 usbi_mutex_static_lock(&active_contexts_lock);
1276 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1277 dev = usbi_get_device_by_session_id (ctx, session_id);
1279 usbi_disconnect_device (dev);
1280 libusb_unref_device(dev);
1282 usbi_dbg("device not found for session %x", session_id);
1285 usbi_mutex_static_unlock(&active_contexts_lock);
1288 #if !defined(USE_UDEV)
1289 /* open a bus directory and adds all discovered devices to the context */
1290 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1293 char dirpath[PATH_MAX];
1294 struct dirent *entry;
1295 int r = LIBUSB_ERROR_IO;
1297 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1298 usbi_dbg("%s", dirpath);
1299 dir = opendir(dirpath);
1301 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1302 /* FIXME: should handle valid race conditions like hub unplugged
1303 * during directory iteration - this is not an error */
1307 while ((entry = readdir(dir))) {
1310 if (entry->d_name[0] == '.')
1313 devaddr = atoi(entry->d_name);
1315 usbi_dbg("unknown dir entry %s", entry->d_name);
1319 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1320 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1331 static int usbfs_get_device_list(struct libusb_context *ctx)
1333 struct dirent *entry;
1334 DIR *buses = opendir(usbfs_path);
1338 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1339 return LIBUSB_ERROR_IO;
1342 while ((entry = readdir(buses))) {
1345 if (entry->d_name[0] == '.')
1350 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1353 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1355 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1359 busnum = atoi(entry->d_name);
1361 usbi_dbg("unknown dir entry %s", entry->d_name);
1365 r = usbfs_scan_busdir(ctx, busnum);
1377 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1379 uint8_t busnum, devaddr;
1382 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1383 if (LIBUSB_SUCCESS != ret) {
1387 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1391 #if !defined(USE_UDEV)
1392 static int sysfs_get_device_list(struct libusb_context *ctx)
1394 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1395 struct dirent *entry;
1396 int r = LIBUSB_ERROR_IO;
1399 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1403 while ((entry = readdir(devices))) {
1404 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1405 || strchr(entry->d_name, ':'))
1408 if (sysfs_scan_device(ctx, entry->d_name)) {
1409 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1420 static int linux_default_scan_devices (struct libusb_context *ctx)
1422 /* we can retrieve device list and descriptors from sysfs or usbfs.
1423 * sysfs is preferable, because if we use usbfs we end up resuming
1424 * any autosuspended USB devices. however, sysfs is not available
1425 * everywhere, so we need a usbfs fallback too.
1427 * as described in the "sysfs vs usbfs" comment at the top of this
1428 * file, sometimes we have sysfs but not enough information to
1429 * relate sysfs devices to usbfs nodes. op_init() determines the
1430 * adequacy of sysfs and sets sysfs_can_relate_devices.
1432 if (sysfs_can_relate_devices != 0)
1433 return sysfs_get_device_list(ctx);
1435 return usbfs_get_device_list(ctx);
1439 static int op_open(struct libusb_device_handle *handle)
1441 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1444 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1445 if (hpriv->fd < 0) {
1446 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1447 /* device will still be marked as attached if hotplug monitor thread
1448 * hasn't processed remove event yet */
1449 usbi_mutex_static_lock(&linux_hotplug_lock);
1450 if (handle->dev->attached) {
1451 usbi_dbg("open failed with no device, but device still attached");
1452 linux_device_disconnected(handle->dev->bus_number,
1453 handle->dev->device_address);
1455 usbi_mutex_static_unlock(&linux_hotplug_lock);
1460 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1462 if (errno == ENOTTY)
1463 usbi_dbg("getcap not available");
1465 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1467 if (supports_flag_zero_packet)
1468 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1469 if (supports_flag_bulk_continuation)
1470 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1473 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1480 static void op_close(struct libusb_device_handle *dev_handle)
1482 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1483 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1484 if (!hpriv->fd_removed)
1485 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1489 static int op_get_configuration(struct libusb_device_handle *handle,
1494 if (sysfs_can_relate_devices) {
1495 r = sysfs_get_active_config(handle->dev, config);
1497 r = usbfs_get_active_config(handle->dev,
1498 _device_handle_priv(handle)->fd);
1499 if (r == LIBUSB_SUCCESS)
1500 *config = _device_priv(handle->dev)->active_config;
1505 if (*config == -1) {
1506 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1513 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1515 struct linux_device_priv *priv = _device_priv(handle->dev);
1516 int fd = _device_handle_priv(handle)->fd;
1517 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1519 if (errno == EINVAL)
1520 return LIBUSB_ERROR_NOT_FOUND;
1521 else if (errno == EBUSY)
1522 return LIBUSB_ERROR_BUSY;
1523 else if (errno == ENODEV)
1524 return LIBUSB_ERROR_NO_DEVICE;
1526 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1527 return LIBUSB_ERROR_OTHER;
1530 /* update our cached active config descriptor */
1531 priv->active_config = config;
1533 return LIBUSB_SUCCESS;
1536 static int claim_interface(struct libusb_device_handle *handle, int iface)
1538 int fd = _device_handle_priv(handle)->fd;
1539 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1541 if (errno == ENOENT)
1542 return LIBUSB_ERROR_NOT_FOUND;
1543 else if (errno == EBUSY)
1544 return LIBUSB_ERROR_BUSY;
1545 else if (errno == ENODEV)
1546 return LIBUSB_ERROR_NO_DEVICE;
1548 usbi_err(HANDLE_CTX(handle),
1549 "claim interface failed, error %d errno %d", r, errno);
1550 return LIBUSB_ERROR_OTHER;
1555 static int release_interface(struct libusb_device_handle *handle, int iface)
1557 int fd = _device_handle_priv(handle)->fd;
1558 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1560 if (errno == ENODEV)
1561 return LIBUSB_ERROR_NO_DEVICE;
1563 usbi_err(HANDLE_CTX(handle),
1564 "release interface failed, error %d errno %d", r, errno);
1565 return LIBUSB_ERROR_OTHER;
1570 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1573 int fd = _device_handle_priv(handle)->fd;
1574 struct usbfs_setinterface setintf;
1577 setintf.interface = iface;
1578 setintf.altsetting = altsetting;
1579 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1581 if (errno == EINVAL)
1582 return LIBUSB_ERROR_NOT_FOUND;
1583 else if (errno == ENODEV)
1584 return LIBUSB_ERROR_NO_DEVICE;
1586 usbi_err(HANDLE_CTX(handle),
1587 "setintf failed error %d errno %d", r, errno);
1588 return LIBUSB_ERROR_OTHER;
1594 static int op_clear_halt(struct libusb_device_handle *handle,
1595 unsigned char endpoint)
1597 int fd = _device_handle_priv(handle)->fd;
1598 unsigned int _endpoint = endpoint;
1599 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1601 if (errno == ENOENT)
1602 return LIBUSB_ERROR_NOT_FOUND;
1603 else if (errno == ENODEV)
1604 return LIBUSB_ERROR_NO_DEVICE;
1606 usbi_err(HANDLE_CTX(handle),
1607 "clear_halt failed error %d errno %d", r, errno);
1608 return LIBUSB_ERROR_OTHER;
1614 static int op_reset_device(struct libusb_device_handle *handle)
1616 int fd = _device_handle_priv(handle)->fd;
1619 /* Doing a device reset will cause the usbfs driver to get unbound
1620 from any interfaces it is bound to. By voluntarily unbinding
1621 the usbfs driver ourself, we stop the kernel from rebinding
1622 the interface after reset (which would end up with the interface
1623 getting bound to the in kernel driver if any). */
1624 for (i = 0; i < USB_MAXINTERFACES; i++) {
1625 if (handle->claimed_interfaces & (1L << i)) {
1626 release_interface(handle, i);
1630 usbi_mutex_lock(&handle->lock);
1631 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1633 if (errno == ENODEV) {
1634 ret = LIBUSB_ERROR_NOT_FOUND;
1638 usbi_err(HANDLE_CTX(handle),
1639 "reset failed error %d errno %d", r, errno);
1640 ret = LIBUSB_ERROR_OTHER;
1644 /* And re-claim any interfaces which were claimed before the reset */
1645 for (i = 0; i < USB_MAXINTERFACES; i++) {
1646 if (handle->claimed_interfaces & (1L << i)) {
1648 * A driver may have completed modprobing during
1649 * IOCTL_USBFS_RESET, and bound itself as soon as
1650 * IOCTL_USBFS_RESET released the device lock
1652 r = detach_kernel_driver_and_claim(handle, i);
1654 usbi_warn(HANDLE_CTX(handle),
1655 "failed to re-claim interface %d after reset: %s",
1656 i, libusb_error_name(r));
1657 handle->claimed_interfaces &= ~(1L << i);
1658 ret = LIBUSB_ERROR_NOT_FOUND;
1663 usbi_mutex_unlock(&handle->lock);
1667 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1668 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1670 int r, fd = _device_handle_priv(handle)->fd;
1671 struct usbfs_streams *streams;
1673 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1674 return LIBUSB_ERROR_INVALID_PARAM;
1676 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1678 return LIBUSB_ERROR_NO_MEM;
1680 streams->num_streams = num_streams;
1681 streams->num_eps = num_endpoints;
1682 memcpy(streams->eps, endpoints, num_endpoints);
1684 r = ioctl(fd, req, streams);
1689 if (errno == ENOTTY)
1690 return LIBUSB_ERROR_NOT_SUPPORTED;
1691 else if (errno == EINVAL)
1692 return LIBUSB_ERROR_INVALID_PARAM;
1693 else if (errno == ENODEV)
1694 return LIBUSB_ERROR_NO_DEVICE;
1696 usbi_err(HANDLE_CTX(handle),
1697 "streams-ioctl failed error %d errno %d", r, errno);
1698 return LIBUSB_ERROR_OTHER;
1703 static int op_alloc_streams(struct libusb_device_handle *handle,
1704 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1706 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1707 num_streams, endpoints, num_endpoints);
1710 static int op_free_streams(struct libusb_device_handle *handle,
1711 unsigned char *endpoints, int num_endpoints)
1713 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1714 endpoints, num_endpoints);
1717 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1720 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1721 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1722 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1723 if (buffer == MAP_FAILED) {
1724 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1731 static int op_dev_mem_free(struct libusb_device_handle *handle,
1732 unsigned char *buffer, size_t len)
1734 if (munmap(buffer, len) != 0) {
1735 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1737 return LIBUSB_ERROR_OTHER;
1739 return LIBUSB_SUCCESS;
1743 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1746 int fd = _device_handle_priv(handle)->fd;
1747 struct usbfs_getdriver getdrv;
1750 getdrv.interface = interface;
1751 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1753 if (errno == ENODATA)
1755 else if (errno == ENODEV)
1756 return LIBUSB_ERROR_NO_DEVICE;
1758 usbi_err(HANDLE_CTX(handle),
1759 "get driver failed error %d errno %d", r, errno);
1760 return LIBUSB_ERROR_OTHER;
1763 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1766 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1769 int fd = _device_handle_priv(handle)->fd;
1770 struct usbfs_ioctl command;
1771 struct usbfs_getdriver getdrv;
1774 command.ifno = interface;
1775 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1776 command.data = NULL;
1778 getdrv.interface = interface;
1779 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1780 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1781 return LIBUSB_ERROR_NOT_FOUND;
1783 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1785 if (errno == ENODATA)
1786 return LIBUSB_ERROR_NOT_FOUND;
1787 else if (errno == EINVAL)
1788 return LIBUSB_ERROR_INVALID_PARAM;
1789 else if (errno == ENODEV)
1790 return LIBUSB_ERROR_NO_DEVICE;
1792 usbi_err(HANDLE_CTX(handle),
1793 "detach failed error %d errno %d", r, errno);
1794 return LIBUSB_ERROR_OTHER;
1800 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1803 int fd = _device_handle_priv(handle)->fd;
1804 struct usbfs_ioctl command;
1807 command.ifno = interface;
1808 command.ioctl_code = IOCTL_USBFS_CONNECT;
1809 command.data = NULL;
1811 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1813 if (errno == ENODATA)
1814 return LIBUSB_ERROR_NOT_FOUND;
1815 else if (errno == EINVAL)
1816 return LIBUSB_ERROR_INVALID_PARAM;
1817 else if (errno == ENODEV)
1818 return LIBUSB_ERROR_NO_DEVICE;
1819 else if (errno == EBUSY)
1820 return LIBUSB_ERROR_BUSY;
1822 usbi_err(HANDLE_CTX(handle),
1823 "attach failed error %d errno %d", r, errno);
1824 return LIBUSB_ERROR_OTHER;
1825 } else if (r == 0) {
1826 return LIBUSB_ERROR_NOT_FOUND;
1832 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1835 struct usbfs_disconnect_claim dc;
1836 int r, fd = _device_handle_priv(handle)->fd;
1838 dc.interface = interface;
1839 strcpy(dc.driver, "usbfs");
1840 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1841 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1842 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1848 return LIBUSB_ERROR_BUSY;
1850 return LIBUSB_ERROR_INVALID_PARAM;
1852 return LIBUSB_ERROR_NO_DEVICE;
1854 usbi_err(HANDLE_CTX(handle),
1855 "disconnect-and-claim failed errno %d", errno);
1856 return LIBUSB_ERROR_OTHER;
1859 /* Fallback code for kernels which don't support the
1860 disconnect-and-claim ioctl */
1861 r = op_detach_kernel_driver(handle, interface);
1862 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1865 return claim_interface(handle, interface);
1868 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1870 if (handle->auto_detach_kernel_driver)
1871 return detach_kernel_driver_and_claim(handle, iface);
1873 return claim_interface(handle, iface);
1876 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1880 r = release_interface(handle, iface);
1884 if (handle->auto_detach_kernel_driver)
1885 op_attach_kernel_driver(handle, iface);
1890 static void op_destroy_device(struct libusb_device *dev)
1892 struct linux_device_priv *priv = _device_priv(dev);
1893 if (priv->descriptors)
1894 free(priv->descriptors);
1895 if (priv->sysfs_dir)
1896 free(priv->sysfs_dir);
1899 /* URBs are discarded in reverse order of submission to avoid races. */
1900 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1902 struct libusb_transfer *transfer =
1903 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904 struct linux_transfer_priv *tpriv =
1905 usbi_transfer_get_os_priv(itransfer);
1906 struct linux_device_handle_priv *dpriv =
1907 _device_handle_priv(transfer->dev_handle);
1909 struct usbfs_urb *urb;
1911 for (i = last_plus_one - 1; i >= first; i--) {
1912 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1913 urb = tpriv->iso_urbs[i];
1915 urb = &tpriv->urbs[i];
1917 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1920 if (EINVAL == errno) {
1921 usbi_dbg("URB not found --> assuming ready to be reaped");
1922 if (i == (last_plus_one - 1))
1923 ret = LIBUSB_ERROR_NOT_FOUND;
1924 } else if (ENODEV == errno) {
1925 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1926 ret = LIBUSB_ERROR_NO_DEVICE;
1928 usbi_warn(TRANSFER_CTX(transfer),
1929 "unrecognised discard errno %d", errno);
1930 ret = LIBUSB_ERROR_OTHER;
1936 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1939 for (i = 0; i < tpriv->num_urbs; i++) {
1940 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1946 free(tpriv->iso_urbs);
1947 tpriv->iso_urbs = NULL;
1950 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1952 struct libusb_transfer *transfer =
1953 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1954 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1955 struct linux_device_handle_priv *dpriv =
1956 _device_handle_priv(transfer->dev_handle);
1957 struct usbfs_urb *urbs;
1958 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1959 == LIBUSB_ENDPOINT_OUT;
1960 int bulk_buffer_len, use_bulk_continuation;
1964 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1965 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1966 return LIBUSB_ERROR_NOT_SUPPORTED;
1969 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1970 * around this by splitting large transfers into 16k blocks, and then
1971 * submit all urbs at once. it would be simpler to submit one urb at
1972 * a time, but there is a big performance gain doing it this way.
1974 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1975 * using arbritary large transfers can still be a bad idea though, as
1976 * the kernel needs to allocate physical contiguous memory for this,
1977 * which may fail for large buffers.
1979 * The kernel solves this problem by splitting the transfer into
1980 * blocks itself when the host-controller is scatter-gather capable
1981 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1983 * Last, there is the issue of short-transfers when splitting, for
1984 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1985 * is needed, but this is not always available.
1987 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1988 /* Good! Just submit everything in one go */
1989 bulk_buffer_len = transfer->length ? transfer->length : 1;
1990 use_bulk_continuation = 0;
1991 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1992 /* Split the transfers and use bulk-continuation to
1993 avoid issues with short-transfers */
1994 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1995 use_bulk_continuation = 1;
1996 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1997 /* Don't split, assume the kernel can alloc the buffer
1998 (otherwise the submit will fail with -ENOMEM) */
1999 bulk_buffer_len = transfer->length ? transfer->length : 1;
2000 use_bulk_continuation = 0;
2002 /* Bad, splitting without bulk-continuation, short transfers
2003 which end before the last urb will not work reliable! */
2004 /* Note we don't warn here as this is "normal" on kernels <
2005 2.6.32 and not a problem for most applications */
2006 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2007 use_bulk_continuation = 0;
2010 int num_urbs = transfer->length / bulk_buffer_len;
2011 int last_urb_partial = 0;
2013 if (transfer->length == 0) {
2015 } else if ((transfer->length % bulk_buffer_len) > 0) {
2016 last_urb_partial = 1;
2019 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2021 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2023 return LIBUSB_ERROR_NO_MEM;
2025 tpriv->num_urbs = num_urbs;
2026 tpriv->num_retired = 0;
2027 tpriv->reap_action = NORMAL;
2028 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2030 for (i = 0; i < num_urbs; i++) {
2031 struct usbfs_urb *urb = &urbs[i];
2032 urb->usercontext = itransfer;
2033 switch (transfer->type) {
2034 case LIBUSB_TRANSFER_TYPE_BULK:
2035 urb->type = USBFS_URB_TYPE_BULK;
2038 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2039 urb->type = USBFS_URB_TYPE_BULK;
2040 urb->stream_id = itransfer->stream_id;
2042 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2043 urb->type = USBFS_URB_TYPE_INTERRUPT;
2046 urb->endpoint = transfer->endpoint;
2047 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2048 /* don't set the short not ok flag for the last URB */
2049 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2050 urb->flags = USBFS_URB_SHORT_NOT_OK;
2051 if (i == num_urbs - 1 && last_urb_partial)
2052 urb->buffer_length = transfer->length % bulk_buffer_len;
2053 else if (transfer->length == 0)
2054 urb->buffer_length = 0;
2056 urb->buffer_length = bulk_buffer_len;
2058 if (i > 0 && use_bulk_continuation)
2059 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2061 /* we have already checked that the flag is supported */
2062 if (is_out && i == num_urbs - 1 &&
2063 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2064 urb->flags |= USBFS_URB_ZERO_PACKET;
2066 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2068 if (errno == ENODEV) {
2069 r = LIBUSB_ERROR_NO_DEVICE;
2071 usbi_err(TRANSFER_CTX(transfer),
2072 "submiturb failed error %d errno=%d", r, errno);
2073 r = LIBUSB_ERROR_IO;
2076 /* if the first URB submission fails, we can simply free up and
2077 * return failure immediately. */
2079 usbi_dbg("first URB failed, easy peasy");
2085 /* if it's not the first URB that failed, the situation is a bit
2086 * tricky. we may need to discard all previous URBs. there are
2088 * - discarding is asynchronous - discarded urbs will be reaped
2089 * later. the user must not have freed the transfer when the
2090 * discarded URBs are reaped, otherwise libusb will be using
2092 * - the earlier URBs may have completed successfully and we do
2093 * not want to throw away any data.
2094 * - this URB failing may be no error; EREMOTEIO means that
2095 * this transfer simply didn't need all the URBs we submitted
2096 * so, we report that the transfer was submitted successfully and
2097 * in case of error we discard all previous URBs. later when
2098 * the final reap completes we can report error to the user,
2099 * or success if an earlier URB was completed successfully.
2101 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2103 /* The URBs we haven't submitted yet we count as already
2105 tpriv->num_retired += num_urbs - i;
2107 /* If we completed short then don't try to discard. */
2108 if (COMPLETED_EARLY == tpriv->reap_action)
2111 discard_urbs(itransfer, 0, i);
2113 usbi_dbg("reporting successful submission but waiting for %d "
2114 "discards before reporting error", i);
2122 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2124 struct libusb_transfer *transfer =
2125 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2126 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2127 struct linux_device_handle_priv *dpriv =
2128 _device_handle_priv(transfer->dev_handle);
2129 struct usbfs_urb **urbs;
2131 int num_packets = transfer->num_iso_packets;
2133 int this_urb_len = 0;
2135 int packet_offset = 0;
2136 unsigned int packet_len;
2137 unsigned char *urb_buffer = transfer->buffer;
2139 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2140 * at least three times, and it's difficult to accurately detect which
2141 * limit this running kernel might impose. so we attempt to submit
2142 * whatever the user has provided. if the kernel rejects the request
2143 * due to its size, we return an error indicating such to the user.
2146 /* calculate how many URBs we need */
2147 for (i = 0; i < num_packets; i++) {
2148 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
2149 packet_len = transfer->iso_packet_desc[i].length;
2151 if (packet_len > space_remaining) {
2153 this_urb_len = packet_len;
2154 /* check that we can actually support this packet length */
2155 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2156 return LIBUSB_ERROR_INVALID_PARAM;
2158 this_urb_len += packet_len;
2161 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2163 urbs = calloc(num_urbs, sizeof(*urbs));
2165 return LIBUSB_ERROR_NO_MEM;
2167 tpriv->iso_urbs = urbs;
2168 tpriv->num_urbs = num_urbs;
2169 tpriv->num_retired = 0;
2170 tpriv->reap_action = NORMAL;
2171 tpriv->iso_packet_offset = 0;
2173 /* allocate + initialize each URB with the correct number of packets */
2174 for (i = 0; i < num_urbs; i++) {
2175 struct usbfs_urb *urb;
2176 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2177 int urb_packet_offset = 0;
2178 unsigned char *urb_buffer_orig = urb_buffer;
2182 /* swallow up all the packets we can fit into this URB */
2183 while (packet_offset < transfer->num_iso_packets) {
2184 packet_len = transfer->iso_packet_desc[packet_offset].length;
2185 if (packet_len <= space_remaining_in_urb) {
2187 urb_packet_offset++;
2189 space_remaining_in_urb -= packet_len;
2190 urb_buffer += packet_len;
2192 /* it can't fit, save it for the next URB */
2197 alloc_size = sizeof(*urb)
2198 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2199 urb = calloc(1, alloc_size);
2201 free_iso_urbs(tpriv);
2202 return LIBUSB_ERROR_NO_MEM;
2206 /* populate packet lengths */
2207 for (j = 0, k = packet_offset - urb_packet_offset;
2208 k < packet_offset; k++, j++) {
2209 packet_len = transfer->iso_packet_desc[k].length;
2210 urb->iso_frame_desc[j].length = packet_len;
2213 urb->usercontext = itransfer;
2214 urb->type = USBFS_URB_TYPE_ISO;
2215 /* FIXME: interface for non-ASAP data? */
2216 urb->flags = USBFS_URB_ISO_ASAP;
2217 urb->endpoint = transfer->endpoint;
2218 urb->number_of_packets = urb_packet_offset;
2219 urb->buffer = urb_buffer_orig;
2223 for (i = 0; i < num_urbs; i++) {
2224 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2226 if (errno == ENODEV) {
2227 r = LIBUSB_ERROR_NO_DEVICE;
2228 } else if (errno == EINVAL) {
2229 usbi_warn(TRANSFER_CTX(transfer),
2230 "submiturb failed, transfer too large");
2231 r = LIBUSB_ERROR_INVALID_PARAM;
2233 usbi_err(TRANSFER_CTX(transfer),
2234 "submiturb failed error %d errno=%d", r, errno);
2235 r = LIBUSB_ERROR_IO;
2238 /* if the first URB submission fails, we can simply free up and
2239 * return failure immediately. */
2241 usbi_dbg("first URB failed, easy peasy");
2242 free_iso_urbs(tpriv);
2246 /* if it's not the first URB that failed, the situation is a bit
2247 * tricky. we must discard all previous URBs. there are
2249 * - discarding is asynchronous - discarded urbs will be reaped
2250 * later. the user must not have freed the transfer when the
2251 * discarded URBs are reaped, otherwise libusb will be using
2253 * - the earlier URBs may have completed successfully and we do
2254 * not want to throw away any data.
2255 * so, in this case we discard all the previous URBs BUT we report
2256 * that the transfer was submitted successfully. then later when
2257 * the final discard completes we can report error to the user.
2259 tpriv->reap_action = SUBMIT_FAILED;
2261 /* The URBs we haven't submitted yet we count as already
2263 tpriv->num_retired = num_urbs - i;
2264 discard_urbs(itransfer, 0, i);
2266 usbi_dbg("reporting successful submission but waiting for %d "
2267 "discards before reporting error", i);
2275 static int submit_control_transfer(struct usbi_transfer *itransfer)
2277 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2278 struct libusb_transfer *transfer =
2279 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2280 struct linux_device_handle_priv *dpriv =
2281 _device_handle_priv(transfer->dev_handle);
2282 struct usbfs_urb *urb;
2285 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2286 return LIBUSB_ERROR_INVALID_PARAM;
2288 urb = calloc(1, sizeof(struct usbfs_urb));
2290 return LIBUSB_ERROR_NO_MEM;
2292 tpriv->num_urbs = 1;
2293 tpriv->reap_action = NORMAL;
2295 urb->usercontext = itransfer;
2296 urb->type = USBFS_URB_TYPE_CONTROL;
2297 urb->endpoint = transfer->endpoint;
2298 urb->buffer = transfer->buffer;
2299 urb->buffer_length = transfer->length;
2301 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2305 if (errno == ENODEV)
2306 return LIBUSB_ERROR_NO_DEVICE;
2308 usbi_err(TRANSFER_CTX(transfer),
2309 "submiturb failed error %d errno=%d", r, errno);
2310 return LIBUSB_ERROR_IO;
2315 static int op_submit_transfer(struct usbi_transfer *itransfer)
2317 struct libusb_transfer *transfer =
2318 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2320 switch (transfer->type) {
2321 case LIBUSB_TRANSFER_TYPE_CONTROL:
2322 return submit_control_transfer(itransfer);
2323 case LIBUSB_TRANSFER_TYPE_BULK:
2324 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2325 return submit_bulk_transfer(itransfer);
2326 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2327 return submit_bulk_transfer(itransfer);
2328 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2329 return submit_iso_transfer(itransfer);
2331 usbi_err(TRANSFER_CTX(transfer),
2332 "unknown endpoint type %d", transfer->type);
2333 return LIBUSB_ERROR_INVALID_PARAM;
2337 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2339 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2340 struct libusb_transfer *transfer =
2341 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2345 return LIBUSB_ERROR_NOT_FOUND;
2347 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2351 switch (transfer->type) {
2352 case LIBUSB_TRANSFER_TYPE_BULK:
2353 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2354 if (tpriv->reap_action == ERROR)
2356 /* else, fall through */
2358 tpriv->reap_action = CANCELLED;
2364 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2366 struct libusb_transfer *transfer =
2367 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2368 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2370 /* urbs can be freed also in submit_transfer so lock mutex first */
2371 switch (transfer->type) {
2372 case LIBUSB_TRANSFER_TYPE_CONTROL:
2373 case LIBUSB_TRANSFER_TYPE_BULK:
2374 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2375 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2381 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2382 if (tpriv->iso_urbs) {
2383 free_iso_urbs(tpriv);
2384 tpriv->iso_urbs = NULL;
2388 usbi_err(TRANSFER_CTX(transfer),
2389 "unknown endpoint type %d", transfer->type);
2393 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2394 struct usbfs_urb *urb)
2396 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2397 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2398 int urb_idx = urb - tpriv->urbs;
2400 usbi_mutex_lock(&itransfer->lock);
2401 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2402 urb_idx + 1, tpriv->num_urbs);
2404 tpriv->num_retired++;
2406 if (tpriv->reap_action != NORMAL) {
2407 /* cancelled, submit_fail, or completed early */
2408 usbi_dbg("abnormal reap: urb status %d", urb->status);
2410 /* even though we're in the process of cancelling, it's possible that
2411 * we may receive some data in these URBs that we don't want to lose.
2413 * 1. while the kernel is cancelling all the packets that make up an
2414 * URB, a few of them might complete. so we get back a successful
2415 * cancellation *and* some data.
2416 * 2. we receive a short URB which marks the early completion condition,
2417 * so we start cancelling the remaining URBs. however, we're too
2418 * slow and another URB completes (or at least completes partially).
2419 * (this can't happen since we always use BULK_CONTINUATION.)
2421 * When this happens, our objectives are not to lose any "surplus" data,
2422 * and also to stick it at the end of the previously-received data
2423 * (closing any holes), so that libusb reports the total amount of
2424 * transferred data and presents it in a contiguous chunk.
2426 if (urb->actual_length > 0) {
2427 unsigned char *target = transfer->buffer + itransfer->transferred;
2428 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2429 if (urb->buffer != target) {
2430 usbi_dbg("moving surplus data from offset %d to offset %d",
2431 (unsigned char *) urb->buffer - transfer->buffer,
2432 target - transfer->buffer);
2433 memmove(target, urb->buffer, urb->actual_length);
2435 itransfer->transferred += urb->actual_length;
2438 if (tpriv->num_retired == tpriv->num_urbs) {
2439 usbi_dbg("abnormal reap: last URB handled, reporting");
2440 if (tpriv->reap_action != COMPLETED_EARLY &&
2441 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2442 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2448 itransfer->transferred += urb->actual_length;
2450 /* Many of these errors can occur on *any* urb of a multi-urb
2451 * transfer. When they do, we tear down the rest of the transfer.
2453 switch (urb->status) {
2456 case -EREMOTEIO: /* short transfer */
2458 case -ENOENT: /* cancelled */
2463 usbi_dbg("device removed");
2464 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2465 goto cancel_remaining;
2467 usbi_dbg("detected endpoint stall");
2468 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2469 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2470 goto cancel_remaining;
2472 /* overflow can only ever occur in the last urb */
2473 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2474 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2475 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2482 usbi_dbg("low level error %d", urb->status);
2483 tpriv->reap_action = ERROR;
2484 goto cancel_remaining;
2486 usbi_warn(ITRANSFER_CTX(itransfer),
2487 "unrecognised urb status %d", urb->status);
2488 tpriv->reap_action = ERROR;
2489 goto cancel_remaining;
2492 /* if we're the last urb or we got less data than requested then we're
2494 if (urb_idx == tpriv->num_urbs - 1) {
2495 usbi_dbg("last URB in transfer --> complete!");
2497 } else if (urb->actual_length < urb->buffer_length) {
2498 usbi_dbg("short transfer %d/%d --> complete!",
2499 urb->actual_length, urb->buffer_length);
2500 if (tpriv->reap_action == NORMAL)
2501 tpriv->reap_action = COMPLETED_EARLY;
2506 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2507 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2509 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2512 /* cancel remaining urbs and wait for their completion before
2513 * reporting results */
2514 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2517 usbi_mutex_unlock(&itransfer->lock);
2523 usbi_mutex_unlock(&itransfer->lock);
2524 return CANCELLED == tpriv->reap_action ?
2525 usbi_handle_transfer_cancellation(itransfer) :
2526 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2529 static int handle_iso_completion(struct usbi_transfer *itransfer,
2530 struct usbfs_urb *urb)
2532 struct libusb_transfer *transfer =
2533 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2534 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2535 int num_urbs = tpriv->num_urbs;
2538 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2540 usbi_mutex_lock(&itransfer->lock);
2541 for (i = 0; i < num_urbs; i++) {
2542 if (urb == tpriv->iso_urbs[i]) {
2548 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2549 usbi_mutex_unlock(&itransfer->lock);
2550 return LIBUSB_ERROR_NOT_FOUND;
2553 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2556 /* copy isochronous results back in */
2558 for (i = 0; i < urb->number_of_packets; i++) {
2559 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2560 struct libusb_iso_packet_descriptor *lib_desc =
2561 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2562 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2563 switch (urb_desc->status) {
2566 case -ENOENT: /* cancelled */
2571 usbi_dbg("device removed");
2572 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2575 usbi_dbg("detected endpoint stall");
2576 lib_desc->status = LIBUSB_TRANSFER_STALL;
2579 usbi_dbg("overflow error");
2580 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2588 usbi_dbg("low-level USB error %d", urb_desc->status);
2589 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2592 usbi_warn(TRANSFER_CTX(transfer),
2593 "unrecognised urb status %d", urb_desc->status);
2594 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2597 lib_desc->actual_length = urb_desc->actual_length;
2600 tpriv->num_retired++;
2602 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2603 usbi_dbg("CANCEL: urb status %d", urb->status);
2605 if (tpriv->num_retired == num_urbs) {
2606 usbi_dbg("CANCEL: last URB handled, reporting");
2607 free_iso_urbs(tpriv);
2608 if (tpriv->reap_action == CANCELLED) {
2609 usbi_mutex_unlock(&itransfer->lock);
2610 return usbi_handle_transfer_cancellation(itransfer);
2612 usbi_mutex_unlock(&itransfer->lock);
2613 return usbi_handle_transfer_completion(itransfer,
2614 LIBUSB_TRANSFER_ERROR);
2620 switch (urb->status) {
2623 case -ENOENT: /* cancelled */
2627 usbi_dbg("device removed");
2628 status = LIBUSB_TRANSFER_NO_DEVICE;
2631 usbi_warn(TRANSFER_CTX(transfer),
2632 "unrecognised urb status %d", urb->status);
2633 status = LIBUSB_TRANSFER_ERROR;
2637 /* if we're the last urb then we're done */
2638 if (urb_idx == num_urbs) {
2639 usbi_dbg("last URB in transfer --> complete!");
2640 free_iso_urbs(tpriv);
2641 usbi_mutex_unlock(&itransfer->lock);
2642 return usbi_handle_transfer_completion(itransfer, status);
2646 usbi_mutex_unlock(&itransfer->lock);
2650 static int handle_control_completion(struct usbi_transfer *itransfer,
2651 struct usbfs_urb *urb)
2653 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2656 usbi_mutex_lock(&itransfer->lock);
2657 usbi_dbg("handling completion status %d", urb->status);
2659 itransfer->transferred += urb->actual_length;
2661 if (tpriv->reap_action == CANCELLED) {
2662 if (urb->status != 0 && urb->status != -ENOENT)
2663 usbi_warn(ITRANSFER_CTX(itransfer),
2664 "cancel: unrecognised urb status %d", urb->status);
2667 usbi_mutex_unlock(&itransfer->lock);
2668 return usbi_handle_transfer_cancellation(itransfer);
2671 switch (urb->status) {
2673 status = LIBUSB_TRANSFER_COMPLETED;
2675 case -ENOENT: /* cancelled */
2676 status = LIBUSB_TRANSFER_CANCELLED;
2680 usbi_dbg("device removed");
2681 status = LIBUSB_TRANSFER_NO_DEVICE;
2684 usbi_dbg("unsupported control request");
2685 status = LIBUSB_TRANSFER_STALL;
2688 usbi_dbg("control overflow error");
2689 status = LIBUSB_TRANSFER_OVERFLOW;
2696 usbi_dbg("low-level bus error occurred");
2697 status = LIBUSB_TRANSFER_ERROR;
2700 usbi_warn(ITRANSFER_CTX(itransfer),
2701 "unrecognised urb status %d", urb->status);
2702 status = LIBUSB_TRANSFER_ERROR;
2708 usbi_mutex_unlock(&itransfer->lock);
2709 return usbi_handle_transfer_completion(itransfer, status);
2712 static int reap_for_handle(struct libusb_device_handle *handle)
2714 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2716 struct usbfs_urb *urb;
2717 struct usbi_transfer *itransfer;
2718 struct libusb_transfer *transfer;
2720 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2721 if (r == -1 && errno == EAGAIN)
2724 if (errno == ENODEV)
2725 return LIBUSB_ERROR_NO_DEVICE;
2727 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2729 return LIBUSB_ERROR_IO;
2732 itransfer = urb->usercontext;
2733 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2735 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2736 urb->actual_length);
2738 switch (transfer->type) {
2739 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2740 return handle_iso_completion(itransfer, urb);
2741 case LIBUSB_TRANSFER_TYPE_BULK:
2742 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2743 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2744 return handle_bulk_completion(itransfer, urb);
2745 case LIBUSB_TRANSFER_TYPE_CONTROL:
2746 return handle_control_completion(itransfer, urb);
2748 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2750 return LIBUSB_ERROR_OTHER;
2754 static int op_handle_events(struct libusb_context *ctx,
2755 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2760 usbi_mutex_lock(&ctx->open_devs_lock);
2761 for (i = 0; i < nfds && num_ready > 0; i++) {
2762 struct pollfd *pollfd = &fds[i];
2763 struct libusb_device_handle *handle;
2764 struct linux_device_handle_priv *hpriv = NULL;
2766 if (!pollfd->revents)
2770 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2771 hpriv = _device_handle_priv(handle);
2772 if (hpriv->fd == pollfd->fd)
2776 if (!hpriv || hpriv->fd != pollfd->fd) {
2777 usbi_err(ctx, "cannot find handle for fd %d",
2782 if (pollfd->revents & POLLERR) {
2783 /* remove the fd from the pollfd set so that it doesn't continuously
2784 * trigger an event, and flag that it has been removed so op_close()
2785 * doesn't try to remove it a second time */
2786 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2787 hpriv->fd_removed = 1;
2789 /* device will still be marked as attached if hotplug monitor thread
2790 * hasn't processed remove event yet */
2791 usbi_mutex_static_lock(&linux_hotplug_lock);
2792 if (handle->dev->attached)
2793 linux_device_disconnected(handle->dev->bus_number,
2794 handle->dev->device_address);
2795 usbi_mutex_static_unlock(&linux_hotplug_lock);
2797 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2799 r = reap_for_handle(handle);
2803 usbi_handle_disconnect(handle);
2808 r = reap_for_handle(handle);
2810 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2818 usbi_mutex_unlock(&ctx->open_devs_lock);
2822 static int op_clock_gettime(int clk_id, struct timespec *tp)
2825 case USBI_CLOCK_MONOTONIC:
2826 return clock_gettime(monotonic_clkid, tp);
2827 case USBI_CLOCK_REALTIME:
2828 return clock_gettime(CLOCK_REALTIME, tp);
2830 return LIBUSB_ERROR_INVALID_PARAM;
2834 #ifdef USBI_TIMERFD_AVAILABLE
2835 static clockid_t op_get_timerfd_clockid(void)
2837 return monotonic_clkid;
2842 const struct usbi_os_backend linux_usbfs_backend = {
2843 .name = "Linux usbfs",
2844 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2847 .get_device_list = NULL,
2848 .hotplug_poll = op_hotplug_poll,
2849 .get_device_descriptor = op_get_device_descriptor,
2850 .get_active_config_descriptor = op_get_active_config_descriptor,
2851 .get_config_descriptor = op_get_config_descriptor,
2852 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2856 .get_configuration = op_get_configuration,
2857 .set_configuration = op_set_configuration,
2858 .claim_interface = op_claim_interface,
2859 .release_interface = op_release_interface,
2861 .set_interface_altsetting = op_set_interface,
2862 .clear_halt = op_clear_halt,
2863 .reset_device = op_reset_device,
2865 .alloc_streams = op_alloc_streams,
2866 .free_streams = op_free_streams,
2868 .dev_mem_alloc = op_dev_mem_alloc,
2869 .dev_mem_free = op_dev_mem_free,
2871 .kernel_driver_active = op_kernel_driver_active,
2872 .detach_kernel_driver = op_detach_kernel_driver,
2873 .attach_kernel_driver = op_attach_kernel_driver,
2875 .destroy_device = op_destroy_device,
2877 .submit_transfer = op_submit_transfer,
2878 .cancel_transfer = op_cancel_transfer,
2879 .clear_transfer_priv = op_clear_transfer_priv,
2881 .handle_events = op_handle_events,
2883 .clock_gettime = op_clock_gettime,
2885 #ifdef USBI_TIMERFD_AVAILABLE
2886 .get_timerfd_clockid = op_get_timerfd_clockid,
2889 .device_priv_size = sizeof(struct linux_device_priv),
2890 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2891 .transfer_priv_size = sizeof(struct linux_transfer_priv),