1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusbx
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>
37 #include <sys/types.h>
38 #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 2.6.32 adds support for a bulk continuation URB flag. this basically
85 * allows us to mark URBs as being part of a specific logical transfer when
86 * we submit them to the kernel. then, on any error except a cancellation, all
87 * URBs within that transfer will be cancelled and no more URBs will be
88 * accepted for the transfer, meaning that no more data can creep in.
90 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
91 * (in either direction) except the first.
92 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
93 * last; it means that the kernel should treat a short reply as an error.
94 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
95 * transfers can't be short unless there's already some sort of error), and
96 * setting this flag is disallowed (a kernel with USB debugging enabled will
99 static int supports_flag_bulk_continuation = -1;
101 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
102 * allows us to mark URBs that should be followed by a zero length data
103 * packet, which can be required by device- or class-specific protocols.
105 static int supports_flag_zero_packet = -1;
107 /* clock ID for monotonic clock, as not all clock sources are available on all
108 * systems. appropriate choice made at initialization time. */
109 static clockid_t monotonic_clkid = -1;
111 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
112 * to sysfs, so we can relate devices. This also implies that we can read
113 * the active configuration through bConfigurationValue */
114 static int sysfs_can_relate_devices = -1;
116 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
117 * config descriptors (rather then just the active config) to the sysfs
118 * descriptors file, so from then on we can use them. */
119 static int sysfs_has_descriptors = -1;
121 /* how many times have we initted (and not exited) ? */
122 static volatile int init_count = 0;
124 /* Serialize hotplug start/stop, scan-devices, event-thread, and poll */
125 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
127 static int linux_start_event_monitor(void);
128 static int linux_stop_event_monitor(void);
129 static int linux_scan_devices(struct libusb_context *ctx);
130 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
131 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
133 #if !defined(USE_UDEV)
134 static int linux_default_scan_devices (struct libusb_context *ctx);
137 struct linux_device_priv {
139 unsigned char *descriptors;
141 int active_config; /* cache val for !sysfs_can_relate_devices */
144 struct linux_device_handle_priv {
151 /* submission failed after the first URB, so await cancellation/completion
152 * of all the others */
155 /* cancelled by user or timeout */
158 /* completed multi-URB transfer in non-final URB */
161 /* one or more urbs encountered a low-level error */
165 struct linux_transfer_priv {
167 struct usbfs_urb *urbs;
168 struct usbfs_urb **iso_urbs;
171 enum reap_action reap_action;
174 enum libusb_transfer_status reap_status;
176 /* next iso packet in user-supplied transfer to be populated */
177 int iso_packet_offset;
180 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
182 struct libusb_context *ctx = DEVICE_CTX(dev);
187 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
188 usbfs_path, dev->bus_number, dev->device_address);
190 snprintf(path, PATH_MAX, "%s/%03d/%03d",
191 usbfs_path, dev->bus_number, dev->device_address);
193 fd = open(path, mode);
195 return fd; /* Success */
198 usbi_err(ctx, "libusbx couldn't open USB device %s: %s",
199 path, strerror(errno));
200 if (errno == EACCES && mode == O_RDWR)
201 usbi_err(ctx, "libusbx requires write access to USB "
206 return LIBUSB_ERROR_ACCESS;
208 return LIBUSB_ERROR_NO_DEVICE;
209 return LIBUSB_ERROR_IO;
212 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
214 return (struct linux_device_priv *) dev->os_priv;
217 static struct linux_device_handle_priv *_device_handle_priv(
218 struct libusb_device_handle *handle)
220 return (struct linux_device_handle_priv *) handle->os_priv;
223 /* check dirent for a /dev/usbdev%d.%d name
224 * optionally return bus/device on success */
225 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
229 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
232 usbi_dbg("found: %s", entry->d_name);
240 static int check_usb_vfs(const char *dirname)
243 struct dirent *entry;
246 dir = opendir(dirname);
250 while ((entry = readdir(dir)) != NULL) {
251 if (entry->d_name[0] == '.')
254 /* We assume if we find any files that it must be the right place */
263 static const char *find_usbfs_path(void)
265 const char *path = "/dev/bus/usb";
266 const char *ret = NULL;
268 if (check_usb_vfs(path)) {
271 path = "/proc/bus/usb";
272 if (check_usb_vfs(path))
276 /* look for /dev/usbdev*.* if the normal places fail */
278 struct dirent *entry;
284 while ((entry = readdir(dir)) != NULL) {
285 if (_is_usbdev_entry(entry, NULL, NULL)) {
286 /* found one; that's enough */
297 usbi_dbg("found usbfs at %s", ret);
302 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
303 * seem to lack it). fall back to REALTIME if we have to. */
304 static clockid_t find_monotonic_clock(void)
306 #ifdef CLOCK_MONOTONIC
310 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
311 * because it's not available through timerfd */
312 r = clock_gettime(CLOCK_MONOTONIC, &ts);
314 return CLOCK_MONOTONIC;
315 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
318 return CLOCK_REALTIME;
321 static int kernel_version_ge(int major, int minor, int sublevel)
324 int atoms, kmajor, kminor, ksublevel;
328 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
337 /* kmajor == major */
339 return 0 == minor && 0 == sublevel;
345 /* kminor == minor */
347 return 0 == sublevel;
349 return ksublevel >= sublevel;
352 static int op_init(struct libusb_context *ctx)
357 usbfs_path = find_usbfs_path();
359 usbi_err(ctx, "could not find usbfs");
360 return LIBUSB_ERROR_OTHER;
363 if (monotonic_clkid == -1)
364 monotonic_clkid = find_monotonic_clock();
366 if (supports_flag_bulk_continuation == -1) {
367 /* bulk continuation URB flag available from Linux 2.6.32 */
368 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
369 if (supports_flag_bulk_continuation == -1) {
370 usbi_err(ctx, "error checking for bulk continuation support");
371 return LIBUSB_ERROR_OTHER;
375 if (supports_flag_bulk_continuation)
376 usbi_dbg("bulk continuation flag supported");
378 if (-1 == supports_flag_zero_packet) {
379 /* zero length packet URB flag fixed since Linux 2.6.31 */
380 supports_flag_zero_packet = kernel_version_ge(2,6,31);
381 if (-1 == supports_flag_zero_packet) {
382 usbi_err(ctx, "error checking for zero length packet support");
383 return LIBUSB_ERROR_OTHER;
387 if (supports_flag_zero_packet)
388 usbi_dbg("zero length packet flag supported");
390 if (-1 == sysfs_has_descriptors) {
391 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
392 sysfs_has_descriptors = kernel_version_ge(2,6,26);
393 if (-1 == sysfs_has_descriptors) {
394 usbi_err(ctx, "error checking for sysfs descriptors");
395 return LIBUSB_ERROR_OTHER;
399 if (-1 == sysfs_can_relate_devices) {
400 /* sysfs has busnum since Linux 2.6.22 */
401 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
402 if (-1 == sysfs_can_relate_devices) {
403 usbi_err(ctx, "error checking for sysfs busnum");
404 return LIBUSB_ERROR_OTHER;
408 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
409 r = stat(SYSFS_DEVICE_PATH, &statbuf);
410 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
411 usbi_warn(ctx, "sysfs not mounted");
412 sysfs_can_relate_devices = 0;
413 sysfs_has_descriptors = 0;
417 if (sysfs_can_relate_devices)
418 usbi_dbg("sysfs can relate devices");
420 if (sysfs_has_descriptors)
421 usbi_dbg("sysfs has complete descriptors");
423 usbi_mutex_static_lock(&linux_hotplug_lock);
425 if (init_count == 0) {
426 /* start up hotplug event handler */
427 r = linux_start_event_monitor();
429 if (r == LIBUSB_SUCCESS) {
430 r = linux_scan_devices(ctx);
431 if (r == LIBUSB_SUCCESS)
433 else if (init_count == 0)
434 linux_stop_event_monitor();
436 usbi_err(ctx, "error starting hotplug event monitor");
437 usbi_mutex_static_unlock(&linux_hotplug_lock);
442 static void op_exit(void)
444 usbi_mutex_static_lock(&linux_hotplug_lock);
445 assert(init_count != 0);
447 /* tear down event handler */
448 (void)linux_stop_event_monitor();
450 usbi_mutex_static_unlock(&linux_hotplug_lock);
453 static int linux_start_event_monitor(void)
455 #if defined(USE_UDEV)
456 return linux_udev_start_event_monitor();
458 return linux_netlink_start_event_monitor();
462 static int linux_stop_event_monitor(void)
464 #if defined(USE_UDEV)
465 return linux_udev_stop_event_monitor();
467 return linux_netlink_stop_event_monitor();
471 static int linux_scan_devices(struct libusb_context *ctx)
473 #if defined(USE_UDEV)
474 return linux_udev_scan_devices(ctx);
476 return linux_default_scan_devices(ctx);
480 static void op_hotplug_poll(void)
482 #if defined(USE_UDEV)
483 linux_udev_hotplug_poll();
485 linux_netlink_hotplug_poll();
489 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
491 struct linux_device_priv *priv = _device_priv(dev);
492 char filename[PATH_MAX];
495 snprintf(filename, PATH_MAX, "%s/%s/%s",
496 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
497 fd = open(filename, O_RDONLY);
499 usbi_err(DEVICE_CTX(dev),
500 "open %s failed ret=%d errno=%d", filename, fd, errno);
501 return LIBUSB_ERROR_IO;
507 /* Note only suitable for attributes which always read >= 0, < 0 is error */
508 static int __read_sysfs_attr(struct libusb_context *ctx,
509 const char *devname, const char *attr)
511 char filename[PATH_MAX];
515 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
517 f = fopen(filename, "r");
519 if (errno == ENOENT) {
520 /* File doesn't exist. Assume the device has been
521 disconnected (see trac ticket #70). */
522 return LIBUSB_ERROR_NO_DEVICE;
524 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
525 return LIBUSB_ERROR_IO;
528 r = fscanf(f, "%d", &value);
531 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
532 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
535 usbi_err(ctx, "%s contains a negative value", filename);
536 return LIBUSB_ERROR_IO;
542 static int op_get_device_descriptor(struct libusb_device *dev,
543 unsigned char *buffer, int *host_endian)
545 struct linux_device_priv *priv = _device_priv(dev);
547 *host_endian = sysfs_has_descriptors ? 0 : 1;
548 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
553 /* read the bConfigurationValue for a device */
554 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
557 char tmp[4] = {0, 0, 0, 0};
562 fd = _open_sysfs_attr(dev, "bConfigurationValue");
566 r = read(fd, tmp, sizeof(tmp));
569 usbi_err(DEVICE_CTX(dev),
570 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
571 return LIBUSB_ERROR_IO;
573 usbi_dbg("device unconfigured");
578 if (tmp[sizeof(tmp) - 1] != 0) {
579 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
580 return LIBUSB_ERROR_IO;
581 } else if (tmp[0] == 0) {
582 usbi_err(DEVICE_CTX(dev), "no configuration value?");
583 return LIBUSB_ERROR_IO;
586 num = strtol(tmp, &endptr, 10);
588 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
589 return LIBUSB_ERROR_IO;
596 int linux_get_device_address (struct libusb_context *ctx, int detached,
597 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
598 const char *sys_name)
602 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
603 /* can't use sysfs to read the bus and device number if the
604 * device has been detached */
605 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
606 if (NULL == dev_node) {
607 return LIBUSB_ERROR_OTHER;
610 /* will this work with all supported kernel versions? */
611 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
612 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
613 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
614 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
617 return LIBUSB_SUCCESS;
620 usbi_dbg("scan %s", sys_name);
622 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
625 if (sysfs_attr > 255)
626 return LIBUSB_ERROR_INVALID_PARAM;
627 *busnum = (uint8_t) sysfs_attr;
629 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
632 if (sysfs_attr > 255)
633 return LIBUSB_ERROR_INVALID_PARAM;
635 *devaddr = (uint8_t) sysfs_attr;
637 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
639 return LIBUSB_SUCCESS;
642 /* Return offset of the next descriptor with the given type */
643 static int seek_to_next_descriptor(struct libusb_context *ctx,
644 uint8_t descriptor_type, unsigned char *buffer, int size)
646 struct usb_descriptor_header header;
649 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
651 return LIBUSB_ERROR_NOT_FOUND;
654 usbi_err(ctx, "short descriptor read %d/2", size);
655 return LIBUSB_ERROR_IO;
657 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
659 if (i && header.bDescriptorType == descriptor_type)
662 usbi_err(ctx, "bLength overflow by %d bytes", -size);
663 return LIBUSB_ERROR_IO;
666 /* Return offset to next config */
667 static int seek_to_next_config(struct libusb_context *ctx,
668 unsigned char *buffer, int size)
670 struct libusb_config_descriptor config;
673 return LIBUSB_ERROR_NOT_FOUND;
675 if (size < LIBUSB_DT_CONFIG_SIZE) {
676 usbi_err(ctx, "short descriptor read %d/%d",
677 size, LIBUSB_DT_CONFIG_SIZE);
678 return LIBUSB_ERROR_IO;
681 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
682 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
683 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
684 config.bDescriptorType);
685 return LIBUSB_ERROR_IO;
689 * In usbfs the config descriptors are config.wTotalLength bytes apart,
690 * with any short reads from the device appearing as holes in the file.
692 * In sysfs wTotalLength is ignored, instead the kernel returns a
693 * config descriptor with verified bLength fields, with descriptors
694 * with an invalid bLength removed.
696 if (sysfs_has_descriptors) {
697 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
699 if (next == LIBUSB_ERROR_NOT_FOUND)
704 if (next != config.wTotalLength)
705 usbi_warn(ctx, "config length mismatch wTotalLength "
706 "%d real %d", config.wTotalLength, next);
709 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
710 usbi_err(ctx, "invalid wTotalLength %d",
711 config.wTotalLength);
712 return LIBUSB_ERROR_IO;
713 } else if (config.wTotalLength > size) {
714 usbi_warn(ctx, "short descriptor read %d/%d",
715 size, config.wTotalLength);
718 return config.wTotalLength;
722 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
723 uint8_t value, unsigned char **buffer, int *host_endian)
725 struct libusb_context *ctx = DEVICE_CTX(dev);
726 struct linux_device_priv *priv = _device_priv(dev);
727 unsigned char *descriptors = priv->descriptors;
728 int size = priv->descriptors_len;
729 struct libusb_config_descriptor *config;
732 /* Unlike the device desc. config descs. are always in raw format */
735 /* Skip device header */
736 descriptors += DEVICE_DESC_LENGTH;
737 size -= DEVICE_DESC_LENGTH;
739 /* Seek till the config is found, or till "EOF" */
741 int next = seek_to_next_config(ctx, descriptors, size);
744 config = (struct libusb_config_descriptor *)descriptors;
745 if (config->bConfigurationValue == value) {
746 *buffer = descriptors;
754 static int op_get_active_config_descriptor(struct libusb_device *dev,
755 unsigned char *buffer, size_t len, int *host_endian)
758 unsigned char *config_desc;
760 if (sysfs_can_relate_devices) {
761 r = sysfs_get_active_config(dev, &config);
765 /* Use cached bConfigurationValue */
766 struct linux_device_priv *priv = _device_priv(dev);
767 config = priv->active_config;
770 return LIBUSB_ERROR_NOT_FOUND;
772 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
778 memcpy(buffer, config_desc, len);
782 static int op_get_config_descriptor(struct libusb_device *dev,
783 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
785 struct linux_device_priv *priv = _device_priv(dev);
786 unsigned char *descriptors = priv->descriptors;
787 int i, r, size = priv->descriptors_len;
789 /* Unlike the device desc. config descs. are always in raw format */
792 /* Skip device header */
793 descriptors += DEVICE_DESC_LENGTH;
794 size -= DEVICE_DESC_LENGTH;
796 /* Seek till the config is found, or till "EOF" */
798 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
801 if (i == config_index)
808 memcpy(buffer, descriptors, len);
812 /* send a control message to retrieve active configuration */
813 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
815 unsigned char active_config = 0;
818 struct usbfs_ctrltransfer ctrl = {
819 .bmRequestType = LIBUSB_ENDPOINT_IN,
820 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
825 .data = &active_config
828 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
831 return LIBUSB_ERROR_NO_DEVICE;
833 /* we hit this error path frequently with buggy devices :( */
834 usbi_warn(DEVICE_CTX(dev),
835 "get_configuration failed ret=%d errno=%d", r, errno);
836 return LIBUSB_ERROR_IO;
839 return active_config;
842 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
843 uint8_t devaddr, const char *sysfs_dir)
845 struct linux_device_priv *priv = _device_priv(dev);
846 struct libusb_context *ctx = DEVICE_CTX(dev);
847 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
851 dev->bus_number = busnum;
852 dev->device_address = devaddr;
855 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
856 if (!priv->sysfs_dir)
857 return LIBUSB_ERROR_NO_MEM;
858 strcpy(priv->sysfs_dir, sysfs_dir);
860 /* Note speed can contain 1.5, in this case __read_sysfs_attr
861 will stop parsing at the '.' and return 1 */
862 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
865 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
866 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
867 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
868 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
870 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
875 /* cache descriptors in memory */
876 if (sysfs_has_descriptors)
877 fd = _open_sysfs_attr(dev, "descriptors");
879 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
884 descriptors_size *= 2;
885 priv->descriptors = usbi_reallocf(priv->descriptors,
887 if (!priv->descriptors) {
889 return LIBUSB_ERROR_NO_MEM;
891 /* usbfs has holes in the file */
892 if (!sysfs_has_descriptors) {
893 memset(priv->descriptors + priv->descriptors_len,
894 0, descriptors_size - priv->descriptors_len);
896 r = read(fd, priv->descriptors + priv->descriptors_len,
897 descriptors_size - priv->descriptors_len);
899 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
902 return LIBUSB_ERROR_IO;
904 priv->descriptors_len += r;
905 } while (priv->descriptors_len == descriptors_size);
909 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
910 usbi_err(ctx, "short descriptor read (%d)",
911 priv->descriptors_len);
912 return LIBUSB_ERROR_IO;
915 if (sysfs_can_relate_devices)
916 return LIBUSB_SUCCESS;
918 /* cache active config */
919 fd = _get_usbfs_fd(dev, O_RDWR, 1);
921 /* cannot send a control message to determine the active
922 * config. just assume the first one is active. */
923 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
924 "active configuration descriptor");
925 if (priv->descriptors_len >=
926 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
927 struct libusb_config_descriptor config;
928 usbi_parse_descriptor(
929 priv->descriptors + DEVICE_DESC_LENGTH,
930 "bbwbbbbb", &config, 0);
931 priv->active_config = config.bConfigurationValue;
933 priv->active_config = -1; /* No config dt */
935 return LIBUSB_SUCCESS;
938 r = usbfs_get_active_config(dev, fd);
940 priv->active_config = r;
943 /* some buggy devices have a configuration 0, but we're
944 * reaching into the corner of a corner case here, so let's
945 * not support buggy devices in these circumstances.
946 * stick to the specs: a configuration value of 0 means
948 usbi_dbg("active cfg 0? assuming unconfigured device");
949 priv->active_config = -1;
951 } else if (r == LIBUSB_ERROR_IO) {
952 /* buggy devices sometimes fail to report their active config.
953 * assume unconfigured and continue the probing */
954 usbi_warn(ctx, "couldn't query active configuration, assuming"
956 priv->active_config = -1;
958 } /* else r < 0, just return the error code */
964 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
966 struct libusb_context *ctx = DEVICE_CTX(dev);
967 struct libusb_device *it;
968 char *parent_sysfs_dir, *tmp;
969 int ret, add_parent = 1;
971 /* XXX -- can we figure out the topology when using usbfs? */
972 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
973 /* either using usbfs or finding the parent of a root hub */
974 return LIBUSB_SUCCESS;
977 parent_sysfs_dir = strdup(sysfs_dir);
978 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
979 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
980 dev->port_number = atoi(tmp + 1);
983 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
985 free (parent_sysfs_dir);
986 return LIBUSB_SUCCESS;
989 /* is the parent a root hub? */
990 if (NULL == strchr(parent_sysfs_dir, '-')) {
991 tmp = parent_sysfs_dir;
992 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
995 return LIBUSB_ERROR_NO_MEM;
1000 /* find the parent in the context */
1001 usbi_mutex_lock(&ctx->usb_devs_lock);
1002 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1003 struct linux_device_priv *priv = _device_priv(it);
1004 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1005 dev->parent_dev = libusb_ref_device(it);
1009 usbi_mutex_unlock(&ctx->usb_devs_lock);
1011 if (!dev->parent_dev && add_parent) {
1012 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1014 sysfs_scan_device(ctx, parent_sysfs_dir);
1019 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1020 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1022 free (parent_sysfs_dir);
1024 return LIBUSB_SUCCESS;
1027 int linux_enumerate_device(struct libusb_context *ctx,
1028 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1030 unsigned long session_id;
1031 struct libusb_device *dev;
1034 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1035 * will be reused. instead we should add a simple sysfs attribute with
1037 session_id = busnum << 8 | devaddr;
1038 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1041 if (usbi_get_device_by_session_id(ctx, session_id)) {
1042 /* device already exists in the context */
1043 usbi_dbg("session_id %ld already exists", session_id);
1044 return LIBUSB_SUCCESS;
1047 usbi_dbg("allocating new device for %d/%d (session %ld)",
1048 busnum, devaddr, session_id);
1049 dev = usbi_alloc_device(ctx, session_id);
1051 return LIBUSB_ERROR_NO_MEM;
1053 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1056 r = usbi_sanitize_device(dev);
1060 r = linux_get_parent_info(dev, sysfs_dir);
1065 libusb_unref_device(dev);
1067 usbi_connect_device(dev);
1072 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1074 struct libusb_context *ctx;
1076 usbi_mutex_static_lock(&active_contexts_lock);
1077 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1078 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1080 usbi_mutex_static_unlock(&active_contexts_lock);
1083 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1085 struct libusb_context *ctx;
1086 struct libusb_device *dev;
1087 unsigned long session_id = busnum << 8 | devaddr;
1089 usbi_mutex_static_lock(&active_contexts_lock);
1090 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1091 dev = usbi_get_device_by_session_id (ctx, session_id);
1093 usbi_disconnect_device (dev);
1095 usbi_dbg("device not found for session %x", session_id);
1098 usbi_mutex_static_unlock(&active_contexts_lock);
1101 #if !defined(USE_UDEV)
1102 /* open a bus directory and adds all discovered devices to the context */
1103 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1106 char dirpath[PATH_MAX];
1107 struct dirent *entry;
1108 int r = LIBUSB_ERROR_IO;
1110 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1111 usbi_dbg("%s", dirpath);
1112 dir = opendir(dirpath);
1114 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1115 /* FIXME: should handle valid race conditions like hub unplugged
1116 * during directory iteration - this is not an error */
1120 while ((entry = readdir(dir))) {
1123 if (entry->d_name[0] == '.')
1126 devaddr = atoi(entry->d_name);
1128 usbi_dbg("unknown dir entry %s", entry->d_name);
1132 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1133 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1144 static int usbfs_get_device_list(struct libusb_context *ctx)
1146 struct dirent *entry;
1147 DIR *buses = opendir(usbfs_path);
1151 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1152 return LIBUSB_ERROR_IO;
1155 while ((entry = readdir(buses))) {
1158 if (entry->d_name[0] == '.')
1163 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1166 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1168 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1172 busnum = atoi(entry->d_name);
1174 usbi_dbg("unknown dir entry %s", entry->d_name);
1178 r = usbfs_scan_busdir(ctx, busnum);
1190 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1192 uint8_t busnum, devaddr;
1195 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1196 if (LIBUSB_SUCCESS != ret) {
1200 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1204 #if !defined(USE_UDEV)
1205 static int sysfs_get_device_list(struct libusb_context *ctx)
1207 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1208 struct dirent *entry;
1209 int r = LIBUSB_ERROR_IO;
1212 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1216 while ((entry = readdir(devices))) {
1217 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1218 || strchr(entry->d_name, ':'))
1221 if (sysfs_scan_device(ctx, entry->d_name)) {
1222 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1233 static int linux_default_scan_devices (struct libusb_context *ctx)
1235 /* we can retrieve device list and descriptors from sysfs or usbfs.
1236 * sysfs is preferable, because if we use usbfs we end up resuming
1237 * any autosuspended USB devices. however, sysfs is not available
1238 * everywhere, so we need a usbfs fallback too.
1240 * as described in the "sysfs vs usbfs" comment at the top of this
1241 * file, sometimes we have sysfs but not enough information to
1242 * relate sysfs devices to usbfs nodes. op_init() determines the
1243 * adequacy of sysfs and sets sysfs_can_relate_devices.
1245 if (sysfs_can_relate_devices != 0)
1246 return sysfs_get_device_list(ctx);
1248 return usbfs_get_device_list(ctx);
1252 static int op_open(struct libusb_device_handle *handle)
1254 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1257 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1261 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1263 if (errno == ENOTTY)
1264 usbi_dbg("getcap not available");
1266 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1268 if (supports_flag_zero_packet)
1269 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1270 if (supports_flag_bulk_continuation)
1271 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1274 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1277 static void op_close(struct libusb_device_handle *dev_handle)
1279 int fd = _device_handle_priv(dev_handle)->fd;
1280 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1284 static int op_get_configuration(struct libusb_device_handle *handle,
1289 if (sysfs_can_relate_devices) {
1290 r = sysfs_get_active_config(handle->dev, config);
1292 r = usbfs_get_active_config(handle->dev,
1293 _device_handle_priv(handle)->fd);
1298 if (*config == -1) {
1299 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1306 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1308 struct linux_device_priv *priv = _device_priv(handle->dev);
1309 int fd = _device_handle_priv(handle)->fd;
1310 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1312 if (errno == EINVAL)
1313 return LIBUSB_ERROR_NOT_FOUND;
1314 else if (errno == EBUSY)
1315 return LIBUSB_ERROR_BUSY;
1316 else if (errno == ENODEV)
1317 return LIBUSB_ERROR_NO_DEVICE;
1319 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1320 return LIBUSB_ERROR_OTHER;
1323 /* update our cached active config descriptor */
1324 priv->active_config = config;
1326 return LIBUSB_SUCCESS;
1329 static int claim_interface(struct libusb_device_handle *handle, int iface)
1331 int fd = _device_handle_priv(handle)->fd;
1332 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1334 if (errno == ENOENT)
1335 return LIBUSB_ERROR_NOT_FOUND;
1336 else if (errno == EBUSY)
1337 return LIBUSB_ERROR_BUSY;
1338 else if (errno == ENODEV)
1339 return LIBUSB_ERROR_NO_DEVICE;
1341 usbi_err(HANDLE_CTX(handle),
1342 "claim interface failed, error %d errno %d", r, errno);
1343 return LIBUSB_ERROR_OTHER;
1348 static int release_interface(struct libusb_device_handle *handle, int iface)
1350 int fd = _device_handle_priv(handle)->fd;
1351 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1353 if (errno == ENODEV)
1354 return LIBUSB_ERROR_NO_DEVICE;
1356 usbi_err(HANDLE_CTX(handle),
1357 "release interface failed, error %d errno %d", r, errno);
1358 return LIBUSB_ERROR_OTHER;
1363 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1366 int fd = _device_handle_priv(handle)->fd;
1367 struct usbfs_setinterface setintf;
1370 setintf.interface = iface;
1371 setintf.altsetting = altsetting;
1372 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1374 if (errno == EINVAL)
1375 return LIBUSB_ERROR_NOT_FOUND;
1376 else if (errno == ENODEV)
1377 return LIBUSB_ERROR_NO_DEVICE;
1379 usbi_err(HANDLE_CTX(handle),
1380 "setintf failed error %d errno %d", r, errno);
1381 return LIBUSB_ERROR_OTHER;
1387 static int op_clear_halt(struct libusb_device_handle *handle,
1388 unsigned char endpoint)
1390 int fd = _device_handle_priv(handle)->fd;
1391 unsigned int _endpoint = endpoint;
1392 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1394 if (errno == ENOENT)
1395 return LIBUSB_ERROR_NOT_FOUND;
1396 else if (errno == ENODEV)
1397 return LIBUSB_ERROR_NO_DEVICE;
1399 usbi_err(HANDLE_CTX(handle),
1400 "clear_halt failed error %d errno %d", r, errno);
1401 return LIBUSB_ERROR_OTHER;
1407 static int op_reset_device(struct libusb_device_handle *handle)
1409 int fd = _device_handle_priv(handle)->fd;
1412 /* Doing a device reset will cause the usbfs driver to get unbound
1413 from any interfaces it is bound to. By voluntarily unbinding
1414 the usbfs driver ourself, we stop the kernel from rebinding
1415 the interface after reset (which would end up with the interface
1416 getting bound to the in kernel driver if any). */
1417 for (i = 0; i < USB_MAXINTERFACES; i++) {
1418 if (handle->claimed_interfaces & (1L << i)) {
1419 release_interface(handle, i);
1423 usbi_mutex_lock(&handle->lock);
1424 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1426 if (errno == ENODEV) {
1427 ret = LIBUSB_ERROR_NOT_FOUND;
1431 usbi_err(HANDLE_CTX(handle),
1432 "reset failed error %d errno %d", r, errno);
1433 ret = LIBUSB_ERROR_OTHER;
1437 /* And re-claim any interfaces which were claimed before the reset */
1438 for (i = 0; i < USB_MAXINTERFACES; i++) {
1439 if (handle->claimed_interfaces & (1L << i)) {
1441 * A driver may have completed modprobing during
1442 * IOCTL_USBFS_RESET, and bound itself as soon as
1443 * IOCTL_USBFS_RESET released the device lock
1445 r = detach_kernel_driver_and_claim(handle, i);
1447 usbi_warn(HANDLE_CTX(handle),
1448 "failed to re-claim interface %d after reset: %s",
1449 i, libusb_error_name(r));
1450 handle->claimed_interfaces &= ~(1L << i);
1451 ret = LIBUSB_ERROR_NOT_FOUND;
1456 usbi_mutex_unlock(&handle->lock);
1460 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1463 int fd = _device_handle_priv(handle)->fd;
1464 struct usbfs_getdriver getdrv;
1467 getdrv.interface = interface;
1468 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1470 if (errno == ENODATA)
1472 else if (errno == ENODEV)
1473 return LIBUSB_ERROR_NO_DEVICE;
1475 usbi_err(HANDLE_CTX(handle),
1476 "get driver failed error %d errno %d", r, errno);
1477 return LIBUSB_ERROR_OTHER;
1480 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1483 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1486 int fd = _device_handle_priv(handle)->fd;
1487 struct usbfs_ioctl command;
1488 struct usbfs_getdriver getdrv;
1491 command.ifno = interface;
1492 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1493 command.data = NULL;
1495 getdrv.interface = interface;
1496 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1497 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1498 return LIBUSB_ERROR_NOT_FOUND;
1500 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1502 if (errno == ENODATA)
1503 return LIBUSB_ERROR_NOT_FOUND;
1504 else if (errno == EINVAL)
1505 return LIBUSB_ERROR_INVALID_PARAM;
1506 else if (errno == ENODEV)
1507 return LIBUSB_ERROR_NO_DEVICE;
1509 usbi_err(HANDLE_CTX(handle),
1510 "detach failed error %d errno %d", r, errno);
1511 return LIBUSB_ERROR_OTHER;
1517 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1520 int fd = _device_handle_priv(handle)->fd;
1521 struct usbfs_ioctl command;
1524 command.ifno = interface;
1525 command.ioctl_code = IOCTL_USBFS_CONNECT;
1526 command.data = NULL;
1528 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1530 if (errno == ENODATA)
1531 return LIBUSB_ERROR_NOT_FOUND;
1532 else if (errno == EINVAL)
1533 return LIBUSB_ERROR_INVALID_PARAM;
1534 else if (errno == ENODEV)
1535 return LIBUSB_ERROR_NO_DEVICE;
1536 else if (errno == EBUSY)
1537 return LIBUSB_ERROR_BUSY;
1539 usbi_err(HANDLE_CTX(handle),
1540 "attach failed error %d errno %d", r, errno);
1541 return LIBUSB_ERROR_OTHER;
1542 } else if (r == 0) {
1543 return LIBUSB_ERROR_NOT_FOUND;
1549 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1552 struct usbfs_disconnect_claim dc;
1553 int r, fd = _device_handle_priv(handle)->fd;
1555 dc.interface = interface;
1556 strcpy(dc.driver, "usbfs");
1557 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1558 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1559 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1565 return LIBUSB_ERROR_BUSY;
1567 return LIBUSB_ERROR_INVALID_PARAM;
1569 return LIBUSB_ERROR_NO_DEVICE;
1571 usbi_err(HANDLE_CTX(handle),
1572 "disconnect-and-claim failed errno %d", errno);
1573 return LIBUSB_ERROR_OTHER;
1576 /* Fallback code for kernels which don't support the
1577 disconnect-and-claim ioctl */
1578 r = op_detach_kernel_driver(handle, interface);
1579 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1582 return claim_interface(handle, interface);
1585 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1587 if (handle->auto_detach_kernel_driver)
1588 return detach_kernel_driver_and_claim(handle, iface);
1590 return claim_interface(handle, iface);
1593 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1597 r = release_interface(handle, iface);
1601 if (handle->auto_detach_kernel_driver)
1602 op_attach_kernel_driver(handle, iface);
1607 static void op_destroy_device(struct libusb_device *dev)
1609 struct linux_device_priv *priv = _device_priv(dev);
1610 if (priv->descriptors)
1611 free(priv->descriptors);
1612 if (priv->sysfs_dir)
1613 free(priv->sysfs_dir);
1616 /* URBs are discarded in reverse order of submission to avoid races. */
1617 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1619 struct libusb_transfer *transfer =
1620 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1621 struct linux_transfer_priv *tpriv =
1622 usbi_transfer_get_os_priv(itransfer);
1623 struct linux_device_handle_priv *dpriv =
1624 _device_handle_priv(transfer->dev_handle);
1626 struct usbfs_urb *urb;
1628 for (i = last_plus_one - 1; i >= first; i--) {
1629 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1630 urb = tpriv->iso_urbs[i];
1632 urb = &tpriv->urbs[i];
1634 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1637 if (EINVAL == errno) {
1638 usbi_dbg("URB not found --> assuming ready to be reaped");
1639 if (i == (last_plus_one - 1))
1640 ret = LIBUSB_ERROR_NOT_FOUND;
1641 } else if (ENODEV == errno) {
1642 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1643 ret = LIBUSB_ERROR_NO_DEVICE;
1645 usbi_warn(TRANSFER_CTX(transfer),
1646 "unrecognised discard errno %d", errno);
1647 ret = LIBUSB_ERROR_OTHER;
1653 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1656 for (i = 0; i < tpriv->num_urbs; i++) {
1657 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1663 free(tpriv->iso_urbs);
1664 tpriv->iso_urbs = NULL;
1667 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1668 unsigned char urb_type)
1670 struct libusb_transfer *transfer =
1671 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1672 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1673 struct linux_device_handle_priv *dpriv =
1674 _device_handle_priv(transfer->dev_handle);
1675 struct usbfs_urb *urbs;
1676 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1677 == LIBUSB_ENDPOINT_OUT;
1678 int bulk_buffer_len, use_bulk_continuation;
1684 return LIBUSB_ERROR_BUSY;
1686 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1687 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1688 return LIBUSB_ERROR_NOT_SUPPORTED;
1691 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1692 * around this by splitting large transfers into 16k blocks, and then
1693 * submit all urbs at once. it would be simpler to submit one urb at
1694 * a time, but there is a big performance gain doing it this way.
1696 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1697 * using arbritary large transfers can still be a bad idea though, as
1698 * the kernel needs to allocate physical contiguous memory for this,
1699 * which may fail for large buffers.
1701 * The kernel solves this problem by splitting the transfer into
1702 * blocks itself when the host-controller is scatter-gather capable
1703 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1705 * Last, there is the issue of short-transfers when splitting, for
1706 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1707 * is needed, but this is not always available.
1709 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1710 /* Good! Just submit everything in one go */
1711 bulk_buffer_len = transfer->length ? transfer->length : 1;
1712 use_bulk_continuation = 0;
1713 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1714 /* Split the transfers and use bulk-continuation to
1715 avoid issues with short-transfers */
1716 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1717 use_bulk_continuation = 1;
1718 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1719 /* Don't split, assume the kernel can alloc the buffer
1720 (otherwise the submit will fail with -ENOMEM) */
1721 bulk_buffer_len = transfer->length ? transfer->length : 1;
1722 use_bulk_continuation = 0;
1724 /* Bad, splitting without bulk-continuation, short transfers
1725 which end before the last urb will not work reliable! */
1726 /* Note we don't warn here as this is "normal" on kernels <
1727 2.6.32 and not a problem for most applications */
1728 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1729 use_bulk_continuation = 0;
1732 int num_urbs = transfer->length / bulk_buffer_len;
1733 int last_urb_partial = 0;
1735 if (transfer->length == 0) {
1737 } else if ((transfer->length % bulk_buffer_len) > 0) {
1738 last_urb_partial = 1;
1741 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1743 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1744 urbs = calloc(1, alloc_size);
1746 return LIBUSB_ERROR_NO_MEM;
1748 tpriv->num_urbs = num_urbs;
1749 tpriv->num_retired = 0;
1750 tpriv->reap_action = NORMAL;
1751 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1753 for (i = 0; i < num_urbs; i++) {
1754 struct usbfs_urb *urb = &urbs[i];
1755 urb->usercontext = itransfer;
1756 urb->type = urb_type;
1757 urb->endpoint = transfer->endpoint;
1758 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1759 /* don't set the short not ok flag for the last URB */
1760 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1761 urb->flags = USBFS_URB_SHORT_NOT_OK;
1762 if (i == num_urbs - 1 && last_urb_partial)
1763 urb->buffer_length = transfer->length % bulk_buffer_len;
1764 else if (transfer->length == 0)
1765 urb->buffer_length = 0;
1767 urb->buffer_length = bulk_buffer_len;
1769 if (i > 0 && use_bulk_continuation)
1770 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1772 /* we have already checked that the flag is supported */
1773 if (is_out && i == num_urbs - 1 &&
1774 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1775 urb->flags |= USBFS_URB_ZERO_PACKET;
1777 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1779 if (errno == ENODEV) {
1780 r = LIBUSB_ERROR_NO_DEVICE;
1782 usbi_err(TRANSFER_CTX(transfer),
1783 "submiturb failed error %d errno=%d", r, errno);
1784 r = LIBUSB_ERROR_IO;
1787 /* if the first URB submission fails, we can simply free up and
1788 * return failure immediately. */
1790 usbi_dbg("first URB failed, easy peasy");
1796 /* if it's not the first URB that failed, the situation is a bit
1797 * tricky. we may need to discard all previous URBs. there are
1799 * - discarding is asynchronous - discarded urbs will be reaped
1800 * later. the user must not have freed the transfer when the
1801 * discarded URBs are reaped, otherwise libusbx will be using
1803 * - the earlier URBs may have completed successfully and we do
1804 * not want to throw away any data.
1805 * - this URB failing may be no error; EREMOTEIO means that
1806 * this transfer simply didn't need all the URBs we submitted
1807 * so, we report that the transfer was submitted successfully and
1808 * in case of error we discard all previous URBs. later when
1809 * the final reap completes we can report error to the user,
1810 * or success if an earlier URB was completed successfully.
1812 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1814 /* The URBs we haven't submitted yet we count as already
1816 tpriv->num_retired += num_urbs - i;
1818 /* If we completed short then don't try to discard. */
1819 if (COMPLETED_EARLY == tpriv->reap_action)
1822 discard_urbs(itransfer, 0, i);
1824 usbi_dbg("reporting successful submission but waiting for %d "
1825 "discards before reporting error", i);
1833 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1835 struct libusb_transfer *transfer =
1836 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1837 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1838 struct linux_device_handle_priv *dpriv =
1839 _device_handle_priv(transfer->dev_handle);
1840 struct usbfs_urb **urbs;
1842 int num_packets = transfer->num_iso_packets;
1844 int this_urb_len = 0;
1846 int packet_offset = 0;
1847 unsigned int packet_len;
1848 unsigned char *urb_buffer = transfer->buffer;
1850 if (tpriv->iso_urbs)
1851 return LIBUSB_ERROR_BUSY;
1853 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1854 * into smaller units to meet such restriction, then fire off all the
1855 * units at once. it would be simpler if we just fired one unit at a time,
1856 * but there is a big performance gain through doing it this way.
1858 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1859 * using arbritary large transfers is still be a bad idea though, as
1860 * the kernel needs to allocate physical contiguous memory for this,
1861 * which may fail for large buffers.
1864 /* calculate how many URBs we need */
1865 for (i = 0; i < num_packets; i++) {
1866 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1867 packet_len = transfer->iso_packet_desc[i].length;
1869 if (packet_len > space_remaining) {
1871 this_urb_len = packet_len;
1873 this_urb_len += packet_len;
1876 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1878 alloc_size = num_urbs * sizeof(*urbs);
1879 urbs = calloc(1, alloc_size);
1881 return LIBUSB_ERROR_NO_MEM;
1883 tpriv->iso_urbs = urbs;
1884 tpriv->num_urbs = num_urbs;
1885 tpriv->num_retired = 0;
1886 tpriv->reap_action = NORMAL;
1887 tpriv->iso_packet_offset = 0;
1889 /* allocate + initialize each URB with the correct number of packets */
1890 for (i = 0; i < num_urbs; i++) {
1891 struct usbfs_urb *urb;
1892 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1893 int urb_packet_offset = 0;
1894 unsigned char *urb_buffer_orig = urb_buffer;
1898 /* swallow up all the packets we can fit into this URB */
1899 while (packet_offset < transfer->num_iso_packets) {
1900 packet_len = transfer->iso_packet_desc[packet_offset].length;
1901 if (packet_len <= space_remaining_in_urb) {
1903 urb_packet_offset++;
1905 space_remaining_in_urb -= packet_len;
1906 urb_buffer += packet_len;
1908 /* it can't fit, save it for the next URB */
1913 alloc_size = sizeof(*urb)
1914 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1915 urb = calloc(1, alloc_size);
1917 free_iso_urbs(tpriv);
1918 return LIBUSB_ERROR_NO_MEM;
1922 /* populate packet lengths */
1923 for (j = 0, k = packet_offset - urb_packet_offset;
1924 k < packet_offset; k++, j++) {
1925 packet_len = transfer->iso_packet_desc[k].length;
1926 urb->iso_frame_desc[j].length = packet_len;
1929 urb->usercontext = itransfer;
1930 urb->type = USBFS_URB_TYPE_ISO;
1931 /* FIXME: interface for non-ASAP data? */
1932 urb->flags = USBFS_URB_ISO_ASAP;
1933 urb->endpoint = transfer->endpoint;
1934 urb->number_of_packets = urb_packet_offset;
1935 urb->buffer = urb_buffer_orig;
1939 for (i = 0; i < num_urbs; i++) {
1940 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1942 if (errno == ENODEV) {
1943 r = LIBUSB_ERROR_NO_DEVICE;
1945 usbi_err(TRANSFER_CTX(transfer),
1946 "submiturb failed error %d errno=%d", r, errno);
1947 r = LIBUSB_ERROR_IO;
1950 /* if the first URB submission fails, we can simply free up and
1951 * return failure immediately. */
1953 usbi_dbg("first URB failed, easy peasy");
1954 free_iso_urbs(tpriv);
1958 /* if it's not the first URB that failed, the situation is a bit
1959 * tricky. we must discard all previous URBs. there are
1961 * - discarding is asynchronous - discarded urbs will be reaped
1962 * later. the user must not have freed the transfer when the
1963 * discarded URBs are reaped, otherwise libusbx will be using
1965 * - the earlier URBs may have completed successfully and we do
1966 * not want to throw away any data.
1967 * so, in this case we discard all the previous URBs BUT we report
1968 * that the transfer was submitted successfully. then later when
1969 * the final discard completes we can report error to the user.
1971 tpriv->reap_action = SUBMIT_FAILED;
1973 /* The URBs we haven't submitted yet we count as already
1975 tpriv->num_retired = num_urbs - i;
1976 discard_urbs(itransfer, 0, i);
1978 usbi_dbg("reporting successful submission but waiting for %d "
1979 "discards before reporting error", i);
1987 static int submit_control_transfer(struct usbi_transfer *itransfer)
1989 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1990 struct libusb_transfer *transfer =
1991 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1992 struct linux_device_handle_priv *dpriv =
1993 _device_handle_priv(transfer->dev_handle);
1994 struct usbfs_urb *urb;
1998 return LIBUSB_ERROR_BUSY;
2000 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2001 return LIBUSB_ERROR_INVALID_PARAM;
2003 urb = calloc(1, sizeof(struct usbfs_urb));
2005 return LIBUSB_ERROR_NO_MEM;
2007 tpriv->num_urbs = 1;
2008 tpriv->reap_action = NORMAL;
2010 urb->usercontext = itransfer;
2011 urb->type = USBFS_URB_TYPE_CONTROL;
2012 urb->endpoint = transfer->endpoint;
2013 urb->buffer = transfer->buffer;
2014 urb->buffer_length = transfer->length;
2016 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2020 if (errno == ENODEV)
2021 return LIBUSB_ERROR_NO_DEVICE;
2023 usbi_err(TRANSFER_CTX(transfer),
2024 "submiturb failed error %d errno=%d", r, errno);
2025 return LIBUSB_ERROR_IO;
2030 static int op_submit_transfer(struct usbi_transfer *itransfer)
2032 struct libusb_transfer *transfer =
2033 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2035 switch (transfer->type) {
2036 case LIBUSB_TRANSFER_TYPE_CONTROL:
2037 return submit_control_transfer(itransfer);
2038 case LIBUSB_TRANSFER_TYPE_BULK:
2039 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2040 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2041 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2042 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2043 return submit_iso_transfer(itransfer);
2045 usbi_err(TRANSFER_CTX(transfer),
2046 "unknown endpoint type %d", transfer->type);
2047 return LIBUSB_ERROR_INVALID_PARAM;
2051 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2053 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2054 struct libusb_transfer *transfer =
2055 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2057 switch (transfer->type) {
2058 case LIBUSB_TRANSFER_TYPE_BULK:
2059 if (tpriv->reap_action == ERROR)
2061 /* else, fall through */
2062 case LIBUSB_TRANSFER_TYPE_CONTROL:
2063 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2064 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2065 tpriv->reap_action = CANCELLED;
2068 usbi_err(TRANSFER_CTX(transfer),
2069 "unknown endpoint type %d", transfer->type);
2070 return LIBUSB_ERROR_INVALID_PARAM;
2074 return LIBUSB_ERROR_NOT_FOUND;
2076 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2079 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2081 struct libusb_transfer *transfer =
2082 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2083 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2085 /* urbs can be freed also in submit_transfer so lock mutex first */
2086 switch (transfer->type) {
2087 case LIBUSB_TRANSFER_TYPE_CONTROL:
2088 case LIBUSB_TRANSFER_TYPE_BULK:
2089 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2090 usbi_mutex_lock(&itransfer->lock);
2094 usbi_mutex_unlock(&itransfer->lock);
2096 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2097 usbi_mutex_lock(&itransfer->lock);
2098 if (tpriv->iso_urbs)
2099 free_iso_urbs(tpriv);
2100 usbi_mutex_unlock(&itransfer->lock);
2103 usbi_err(TRANSFER_CTX(transfer),
2104 "unknown endpoint type %d", transfer->type);
2108 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2109 struct usbfs_urb *urb)
2111 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2112 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2113 int urb_idx = urb - tpriv->urbs;
2115 usbi_mutex_lock(&itransfer->lock);
2116 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2117 urb_idx + 1, tpriv->num_urbs);
2119 tpriv->num_retired++;
2121 if (tpriv->reap_action != NORMAL) {
2122 /* cancelled, submit_fail, or completed early */
2123 usbi_dbg("abnormal reap: urb status %d", urb->status);
2125 /* even though we're in the process of cancelling, it's possible that
2126 * we may receive some data in these URBs that we don't want to lose.
2128 * 1. while the kernel is cancelling all the packets that make up an
2129 * URB, a few of them might complete. so we get back a successful
2130 * cancellation *and* some data.
2131 * 2. we receive a short URB which marks the early completion condition,
2132 * so we start cancelling the remaining URBs. however, we're too
2133 * slow and another URB completes (or at least completes partially).
2134 * (this can't happen since we always use BULK_CONTINUATION.)
2136 * When this happens, our objectives are not to lose any "surplus" data,
2137 * and also to stick it at the end of the previously-received data
2138 * (closing any holes), so that libusbx reports the total amount of
2139 * transferred data and presents it in a contiguous chunk.
2141 if (urb->actual_length > 0) {
2142 unsigned char *target = transfer->buffer + itransfer->transferred;
2143 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2144 if (urb->buffer != target) {
2145 usbi_dbg("moving surplus data from offset %d to offset %d",
2146 (unsigned char *) urb->buffer - transfer->buffer,
2147 target - transfer->buffer);
2148 memmove(target, urb->buffer, urb->actual_length);
2150 itransfer->transferred += urb->actual_length;
2153 if (tpriv->num_retired == tpriv->num_urbs) {
2154 usbi_dbg("abnormal reap: last URB handled, reporting");
2155 if (tpriv->reap_action != COMPLETED_EARLY &&
2156 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2157 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2163 itransfer->transferred += urb->actual_length;
2165 /* Many of these errors can occur on *any* urb of a multi-urb
2166 * transfer. When they do, we tear down the rest of the transfer.
2168 switch (urb->status) {
2171 case -EREMOTEIO: /* short transfer */
2173 case -ENOENT: /* cancelled */
2178 usbi_dbg("device removed");
2179 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2180 goto cancel_remaining;
2182 usbi_dbg("detected endpoint stall");
2183 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2184 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2185 goto cancel_remaining;
2187 /* overflow can only ever occur in the last urb */
2188 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2189 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2190 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2197 usbi_dbg("low level error %d", urb->status);
2198 tpriv->reap_action = ERROR;
2199 goto cancel_remaining;
2201 usbi_warn(ITRANSFER_CTX(itransfer),
2202 "unrecognised urb status %d", urb->status);
2203 tpriv->reap_action = ERROR;
2204 goto cancel_remaining;
2207 /* if we're the last urb or we got less data than requested then we're
2209 if (urb_idx == tpriv->num_urbs - 1) {
2210 usbi_dbg("last URB in transfer --> complete!");
2212 } else if (urb->actual_length < urb->buffer_length) {
2213 usbi_dbg("short transfer %d/%d --> complete!",
2214 urb->actual_length, urb->buffer_length);
2215 if (tpriv->reap_action == NORMAL)
2216 tpriv->reap_action = COMPLETED_EARLY;
2221 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2222 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2224 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2227 /* cancel remaining urbs and wait for their completion before
2228 * reporting results */
2229 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2232 usbi_mutex_unlock(&itransfer->lock);
2238 usbi_mutex_unlock(&itransfer->lock);
2239 return CANCELLED == tpriv->reap_action ?
2240 usbi_handle_transfer_cancellation(itransfer) :
2241 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2244 static int handle_iso_completion(struct usbi_transfer *itransfer,
2245 struct usbfs_urb *urb)
2247 struct libusb_transfer *transfer =
2248 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2249 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2250 int num_urbs = tpriv->num_urbs;
2253 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2255 usbi_mutex_lock(&itransfer->lock);
2256 for (i = 0; i < num_urbs; i++) {
2257 if (urb == tpriv->iso_urbs[i]) {
2263 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2264 usbi_mutex_unlock(&itransfer->lock);
2265 return LIBUSB_ERROR_NOT_FOUND;
2268 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2271 /* copy isochronous results back in */
2273 for (i = 0; i < urb->number_of_packets; i++) {
2274 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2275 struct libusb_iso_packet_descriptor *lib_desc =
2276 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2277 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2278 switch (urb_desc->status) {
2281 case -ENOENT: /* cancelled */
2286 usbi_dbg("device removed");
2287 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2290 usbi_dbg("detected endpoint stall");
2291 lib_desc->status = LIBUSB_TRANSFER_STALL;
2294 usbi_dbg("overflow error");
2295 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2303 usbi_dbg("low-level USB error %d", urb_desc->status);
2304 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2307 usbi_warn(TRANSFER_CTX(transfer),
2308 "unrecognised urb status %d", urb_desc->status);
2309 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2312 lib_desc->actual_length = urb_desc->actual_length;
2315 tpriv->num_retired++;
2317 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2318 usbi_dbg("CANCEL: urb status %d", urb->status);
2320 if (tpriv->num_retired == num_urbs) {
2321 usbi_dbg("CANCEL: last URB handled, reporting");
2322 free_iso_urbs(tpriv);
2323 if (tpriv->reap_action == CANCELLED) {
2324 usbi_mutex_unlock(&itransfer->lock);
2325 return usbi_handle_transfer_cancellation(itransfer);
2327 usbi_mutex_unlock(&itransfer->lock);
2328 return usbi_handle_transfer_completion(itransfer,
2329 LIBUSB_TRANSFER_ERROR);
2335 switch (urb->status) {
2338 case -ENOENT: /* cancelled */
2342 usbi_dbg("device removed");
2343 status = LIBUSB_TRANSFER_NO_DEVICE;
2346 usbi_warn(TRANSFER_CTX(transfer),
2347 "unrecognised urb status %d", urb->status);
2348 status = LIBUSB_TRANSFER_ERROR;
2352 /* if we're the last urb then we're done */
2353 if (urb_idx == num_urbs) {
2354 usbi_dbg("last URB in transfer --> complete!");
2355 free_iso_urbs(tpriv);
2356 usbi_mutex_unlock(&itransfer->lock);
2357 return usbi_handle_transfer_completion(itransfer, status);
2361 usbi_mutex_unlock(&itransfer->lock);
2365 static int handle_control_completion(struct usbi_transfer *itransfer,
2366 struct usbfs_urb *urb)
2368 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2371 usbi_mutex_lock(&itransfer->lock);
2372 usbi_dbg("handling completion status %d", urb->status);
2374 itransfer->transferred += urb->actual_length;
2376 if (tpriv->reap_action == CANCELLED) {
2377 if (urb->status != 0 && urb->status != -ENOENT)
2378 usbi_warn(ITRANSFER_CTX(itransfer),
2379 "cancel: unrecognised urb status %d", urb->status);
2382 usbi_mutex_unlock(&itransfer->lock);
2383 return usbi_handle_transfer_cancellation(itransfer);
2386 switch (urb->status) {
2388 status = LIBUSB_TRANSFER_COMPLETED;
2390 case -ENOENT: /* cancelled */
2391 status = LIBUSB_TRANSFER_CANCELLED;
2395 usbi_dbg("device removed");
2396 status = LIBUSB_TRANSFER_NO_DEVICE;
2399 usbi_dbg("unsupported control request");
2400 status = LIBUSB_TRANSFER_STALL;
2403 usbi_dbg("control overflow error");
2404 status = LIBUSB_TRANSFER_OVERFLOW;
2411 usbi_dbg("low-level bus error occurred");
2412 status = LIBUSB_TRANSFER_ERROR;
2415 usbi_warn(ITRANSFER_CTX(itransfer),
2416 "unrecognised urb status %d", urb->status);
2417 status = LIBUSB_TRANSFER_ERROR;
2423 usbi_mutex_unlock(&itransfer->lock);
2424 return usbi_handle_transfer_completion(itransfer, status);
2427 static int reap_for_handle(struct libusb_device_handle *handle)
2429 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2431 struct usbfs_urb *urb;
2432 struct usbi_transfer *itransfer;
2433 struct libusb_transfer *transfer;
2435 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2436 if (r == -1 && errno == EAGAIN)
2439 if (errno == ENODEV)
2440 return LIBUSB_ERROR_NO_DEVICE;
2442 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2444 return LIBUSB_ERROR_IO;
2447 itransfer = urb->usercontext;
2448 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2450 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2451 urb->actual_length);
2453 switch (transfer->type) {
2454 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2455 return handle_iso_completion(itransfer, urb);
2456 case LIBUSB_TRANSFER_TYPE_BULK:
2457 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2458 return handle_bulk_completion(itransfer, urb);
2459 case LIBUSB_TRANSFER_TYPE_CONTROL:
2460 return handle_control_completion(itransfer, urb);
2462 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2464 return LIBUSB_ERROR_OTHER;
2468 static int op_handle_events(struct libusb_context *ctx,
2469 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2474 usbi_mutex_lock(&ctx->open_devs_lock);
2475 for (i = 0; i < nfds && num_ready > 0; i++) {
2476 struct pollfd *pollfd = &fds[i];
2477 struct libusb_device_handle *handle;
2478 struct linux_device_handle_priv *hpriv = NULL;
2480 if (!pollfd->revents)
2484 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2485 hpriv = _device_handle_priv(handle);
2486 if (hpriv->fd == pollfd->fd)
2490 if (pollfd->revents & POLLERR) {
2491 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2492 usbi_handle_disconnect(handle);
2497 r = reap_for_handle(handle);
2499 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2507 usbi_mutex_unlock(&ctx->open_devs_lock);
2511 static int op_clock_gettime(int clk_id, struct timespec *tp)
2514 case USBI_CLOCK_MONOTONIC:
2515 return clock_gettime(monotonic_clkid, tp);
2516 case USBI_CLOCK_REALTIME:
2517 return clock_gettime(CLOCK_REALTIME, tp);
2519 return LIBUSB_ERROR_INVALID_PARAM;
2523 #ifdef USBI_TIMERFD_AVAILABLE
2524 static clockid_t op_get_timerfd_clockid(void)
2526 return monotonic_clkid;
2531 const struct usbi_os_backend linux_usbfs_backend = {
2532 .name = "Linux usbfs",
2533 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2536 .get_device_list = NULL,
2537 .hotplug_poll = op_hotplug_poll,
2538 .get_device_descriptor = op_get_device_descriptor,
2539 .get_active_config_descriptor = op_get_active_config_descriptor,
2540 .get_config_descriptor = op_get_config_descriptor,
2541 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2545 .get_configuration = op_get_configuration,
2546 .set_configuration = op_set_configuration,
2547 .claim_interface = op_claim_interface,
2548 .release_interface = op_release_interface,
2550 .set_interface_altsetting = op_set_interface,
2551 .clear_halt = op_clear_halt,
2552 .reset_device = op_reset_device,
2554 .kernel_driver_active = op_kernel_driver_active,
2555 .detach_kernel_driver = op_detach_kernel_driver,
2556 .attach_kernel_driver = op_attach_kernel_driver,
2558 .destroy_device = op_destroy_device,
2560 .submit_transfer = op_submit_transfer,
2561 .cancel_transfer = op_cancel_transfer,
2562 .clear_transfer_priv = op_clear_transfer_priv,
2564 .handle_events = op_handle_events,
2566 .clock_gettime = op_clock_gettime,
2568 #ifdef USBI_TIMERFD_AVAILABLE
2569 .get_timerfd_clockid = op_get_timerfd_clockid,
2572 .device_priv_size = sizeof(struct linux_device_priv),
2573 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2574 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2575 .add_iso_packet_size = 0,