2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #include <sys/utsname.h>
39 #include "linux_usbfs.h"
42 * opening a usbfs node causes the device to be resumed, so we attempt to
43 * avoid this during enumeration.
45 * sysfs allows us to read the kernel's in-memory copies of device descriptors
46 * and so forth, avoiding the need to open the device:
47 * - The binary "descriptors" file was added in 2.6.23.
48 * - The "busnum" file was added in 2.6.22
49 * - The "devnum" file has been present since pre-2.6.18
50 * - the "bConfigurationValue" file has been present since pre-2.6.18
52 * If we have bConfigurationValue, busnum, and devnum, then we can determine
53 * the active configuration without having to open the usbfs node in RDWR mode.
54 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
55 * The busnum file is important as that is the only way we can relate sysfs
56 * devices to usbfs nodes.
58 * If we also have descriptors, we can obtain the device descriptor and active
59 * configuration without touching usbfs at all.
61 * The descriptors file originally only contained the active configuration
62 * descriptor alongside the device descriptor, but all configurations are
63 * included as of Linux 2.6.26.
66 /* endianness for multi-byte fields:
68 * Descriptors exposed by usbfs have the multi-byte fields in the device
69 * descriptor as host endian. Multi-byte fields in the other descriptors are
70 * bus-endian. The kernel documentation says otherwise, but it is wrong.
73 static const char *usbfs_path = NULL;
75 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
76 static int usbdev_names = 0;
78 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
79 * allows us to mark URBs as being part of a specific logical transfer when
80 * we submit them to the kernel. then, on any error except a cancellation, all
81 * URBs within that transfer will be cancelled and no more URBs will be
82 * accepted for the transfer, meaning that no more data can creep in.
84 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
85 * (in either direction) except the first.
86 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
87 * last; it means that the kernel should treat a short reply as an error.
88 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
89 * transfers can't be short unless there's already some sort of error), and
90 * setting this flag is disallowed (a kernel with USB debugging enabled will
93 static int supports_flag_bulk_continuation = -1;
95 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
96 * allows us to mark URBs that should be followed by a zero length data
97 * packet, which can be required by device- or class-specific protocols.
99 static int supports_flag_zero_packet = -1;
101 /* clock ID for monotonic clock, as not all clock sources are available on all
102 * systems. appropriate choice made at initialization time. */
103 static clockid_t monotonic_clkid = -1;
105 /* do we have a busnum to relate devices? this also implies that we can read
106 * the active configuration through bConfigurationValue */
107 static int sysfs_can_relate_devices = 0;
109 /* do we have a descriptors file? */
110 static int sysfs_has_descriptors = 0;
112 /* how many times have we initted (and not exited) ? */
113 static volatile int init_count = 0;
115 /* Protects init_count and serializes scan_devices versus the hotplug-thread */
116 static usbi_mutex_static_t hotplug_lock = USBI_MUTEX_INITIALIZER;
118 static int linux_start_event_monitor(void);
119 static int linux_stop_event_monitor(void);
120 static int linux_scan_devices(struct libusb_context *ctx);
121 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
123 #if !defined(USE_UDEV)
124 static int linux_default_scan_devices (struct libusb_context *ctx);
127 struct linux_device_priv {
129 unsigned char *dev_descriptor;
130 unsigned char *config_descriptor;
133 struct linux_device_handle_priv {
140 /* submission failed after the first URB, so await cancellation/completion
141 * of all the others */
144 /* cancelled by user or timeout */
147 /* completed multi-URB transfer in non-final URB */
150 /* one or more urbs encountered a low-level error */
154 struct linux_transfer_priv {
156 struct usbfs_urb *urbs;
157 struct usbfs_urb **iso_urbs;
160 enum reap_action reap_action;
163 enum libusb_transfer_status reap_status;
165 /* next iso packet in user-supplied transfer to be populated */
166 int iso_packet_offset;
169 static void _get_usbfs_path(struct libusb_device *dev, char *path)
172 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
173 usbfs_path, dev->bus_number, dev->device_address);
175 snprintf(path, PATH_MAX, "%s/%03d/%03d",
176 usbfs_path, dev->bus_number, dev->device_address);
179 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
181 return (struct linux_device_priv *) dev->os_priv;
184 static struct linux_device_handle_priv *_device_handle_priv(
185 struct libusb_device_handle *handle)
187 return (struct linux_device_handle_priv *) handle->os_priv;
190 /* check dirent for a /dev/usbdev%d.%d name
191 * optionally return bus/device on success */
192 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
196 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
199 usbi_dbg("found: %s", entry->d_name);
207 static int check_usb_vfs(const char *dirname)
210 struct dirent *entry;
213 dir = opendir(dirname);
217 while ((entry = readdir(dir)) != NULL) {
218 if (entry->d_name[0] == '.')
221 /* We assume if we find any files that it must be the right place */
230 static const char *find_usbfs_path(void)
232 const char *path = "/dev/bus/usb";
233 const char *ret = NULL;
235 if (check_usb_vfs(path)) {
238 path = "/proc/bus/usb";
239 if (check_usb_vfs(path))
243 /* look for /dev/usbdev*.* if the normal places fail */
245 struct dirent *entry;
251 while ((entry = readdir(dir)) != NULL) {
252 if (_is_usbdev_entry(entry, NULL, NULL)) {
253 /* found one; that's enough */
264 usbi_dbg("found usbfs at %s", ret);
269 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
270 * seem to lack it). fall back to REALTIME if we have to. */
271 static clockid_t find_monotonic_clock(void)
273 #ifdef CLOCK_MONOTONIC
277 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
278 * because it's not available through timerfd */
279 r = clock_gettime(CLOCK_MONOTONIC, &ts);
281 return CLOCK_MONOTONIC;
282 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
285 return CLOCK_REALTIME;
288 static int kernel_version_ge(int major, int minor, int sublevel)
291 int atoms, kmajor, kminor, ksublevel;
295 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
304 /* kmajor == major */
306 return 0 == minor && 0 == sublevel;
312 /* kminor == minor */
314 return 0 == sublevel;
316 return ksublevel >= sublevel;
319 /* Return 1 if filename exists inside dirname in sysfs.
320 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
321 static int sysfs_has_file(const char *dirname, const char *filename)
327 snprintf(path, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, dirname, filename);
328 r = stat(path, &statbuf);
329 if (r == 0 && S_ISREG(statbuf.st_mode))
335 static int op_init(struct libusb_context *ctx)
340 usbfs_path = find_usbfs_path();
342 usbi_err(ctx, "could not find usbfs");
343 return LIBUSB_ERROR_OTHER;
346 if (monotonic_clkid == -1)
347 monotonic_clkid = find_monotonic_clock();
349 if (supports_flag_bulk_continuation == -1) {
350 /* bulk continuation URB flag available from Linux 2.6.32 */
351 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
352 if (supports_flag_bulk_continuation == -1) {
353 usbi_err(ctx, "error checking for bulk continuation support");
354 return LIBUSB_ERROR_OTHER;
358 if (supports_flag_bulk_continuation)
359 usbi_dbg("bulk continuation flag supported");
361 if (-1 == supports_flag_zero_packet) {
362 /* zero length packet URB flag fixed since Linux 2.6.31 */
363 supports_flag_zero_packet = kernel_version_ge(2,6,31);
364 if (-1 == supports_flag_zero_packet) {
365 usbi_err(ctx, "error checking for zero length packet support");
366 return LIBUSB_ERROR_OTHER;
370 if (supports_flag_zero_packet)
371 usbi_dbg("zero length packet flag supported");
373 r = stat(SYSFS_DEVICE_PATH, &statbuf);
374 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
375 DIR *devices = opendir(SYSFS_DEVICE_PATH);
376 struct dirent *entry;
378 usbi_dbg("found usb devices in sysfs");
381 usbi_err(ctx, "opendir devices failed errno=%d", errno);
382 return LIBUSB_ERROR_IO;
385 /* Make sure sysfs supports all the required files. If it
386 * does not, then usbfs will be used instead. Determine
387 * this by looping through the directories in
388 * SYSFS_DEVICE_PATH. With the assumption that there will
389 * always be subdirectories of the name usbN (usb1, usb2,
390 * etc) representing the root hubs, check the usbN
391 * subdirectories to see if they have all the needed files.
392 * This algorithm uses the usbN subdirectories (root hubs)
393 * because a device disconnection will cause a race
394 * condition regarding which files are available, sometimes
395 * causing an incorrect result. The root hubs are used
396 * because it is assumed that they will always be present.
397 * See the "sysfs vs usbfs" comment at the top of this file
398 * for more details. */
399 while ((entry = readdir(devices))) {
400 int has_busnum=0, has_devnum=0, has_descriptors=0;
401 int has_configuration_value=0;
403 /* Only check the usbN directories. */
404 if (strncmp(entry->d_name, "usb", 3) != 0)
407 /* Check for the files libusbx needs from sysfs. */
408 has_busnum = sysfs_has_file(entry->d_name, "busnum");
409 has_devnum = sysfs_has_file(entry->d_name, "devnum");
410 has_descriptors = sysfs_has_file(entry->d_name, "descriptors");
411 has_configuration_value = sysfs_has_file(entry->d_name, "bConfigurationValue");
413 if (has_busnum && has_devnum && has_configuration_value)
414 sysfs_can_relate_devices = 1;
416 sysfs_has_descriptors = 1;
418 /* Only need to check until we've found ONE device which
419 has all the attributes. */
420 if (sysfs_has_descriptors && sysfs_can_relate_devices)
425 /* Only use sysfs descriptors if the rest of
426 sysfs will work for libusb. */
427 if (!sysfs_can_relate_devices)
428 sysfs_has_descriptors = 0;
430 usbi_dbg("sysfs usb info not available");
431 sysfs_has_descriptors = 0;
432 sysfs_can_relate_devices = 0;
435 usbi_mutex_static_lock(&hotplug_lock);
438 /* start up hotplug event handler */
439 r = linux_start_event_monitor();
440 if (LIBUSB_SUCCESS != r) {
441 usbi_err(ctx, "error starting hotplug event monitor");
444 if (r == LIBUSB_SUCCESS)
445 r = linux_scan_devices(ctx);
446 usbi_mutex_static_unlock(&hotplug_lock);
451 static void op_exit(void)
454 /* should not happen */
458 usbi_mutex_static_lock(&hotplug_lock);
460 /* tear down event handler */
461 (void)linux_stop_event_monitor();
463 usbi_mutex_static_unlock(&hotplug_lock);
466 static int linux_start_event_monitor(void)
468 #if defined(USE_UDEV)
469 return linux_udev_start_event_monitor();
471 return linux_netlink_start_event_monitor();
475 static int linux_stop_event_monitor(void)
477 #if defined(USE_UDEV)
478 return linux_udev_stop_event_monitor();
480 return linux_netlink_stop_event_monitor();
484 static int linux_scan_devices(struct libusb_context *ctx)
486 #if defined(USE_UDEV)
487 return linux_udev_scan_devices(ctx);
489 return linux_default_scan_devices(ctx);
493 static int usbfs_get_device_descriptor(struct libusb_device *dev,
494 unsigned char *buffer)
496 struct linux_device_priv *priv = _device_priv(dev);
498 /* return cached copy */
499 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
503 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
505 struct linux_device_priv *priv = _device_priv(dev);
506 char filename[PATH_MAX];
509 snprintf(filename, PATH_MAX, "%s/%s/%s",
510 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
511 fd = open(filename, O_RDONLY);
513 usbi_err(DEVICE_CTX(dev),
514 "open %s failed ret=%d errno=%d", filename, fd, errno);
515 return LIBUSB_ERROR_IO;
521 /* Note only suitable for attributes which always read >= 0, < 0 is error */
522 static int __read_sysfs_attr(struct libusb_context *ctx,
523 const char *devname, const char *attr)
525 char filename[PATH_MAX];
529 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
531 f = fopen(filename, "r");
533 if (errno == ENOENT) {
534 /* File doesn't exist. Assume the device has been
535 disconnected (see trac ticket #70). */
536 return LIBUSB_ERROR_NO_DEVICE;
538 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
539 return LIBUSB_ERROR_IO;
542 r = fscanf(f, "%d", &value);
545 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
546 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
549 usbi_err(ctx, "%s contains a negative value", filename);
550 return LIBUSB_ERROR_IO;
556 static int sysfs_get_device_descriptor(struct libusb_device *dev,
557 unsigned char *buffer)
562 /* sysfs provides access to an in-memory copy of the device descriptor,
563 * so we use that rather than keeping our own copy */
565 fd = _open_sysfs_attr(dev, "descriptors");
569 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
572 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
573 return LIBUSB_ERROR_IO;
574 } else if (r < DEVICE_DESC_LENGTH) {
575 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
576 return LIBUSB_ERROR_IO;
582 static int op_get_device_descriptor(struct libusb_device *dev,
583 unsigned char *buffer, int *host_endian)
585 if (sysfs_has_descriptors) {
587 return sysfs_get_device_descriptor(dev, buffer);
590 return usbfs_get_device_descriptor(dev, buffer);
594 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
595 unsigned char *buffer, size_t len)
597 struct linux_device_priv *priv = _device_priv(dev);
598 if (!priv->config_descriptor)
599 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
601 /* retrieve cached copy */
602 memcpy(buffer, priv->config_descriptor, len);
606 /* read the bConfigurationValue for a device */
607 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
610 char tmp[4] = {0, 0, 0, 0};
615 fd = _open_sysfs_attr(dev, "bConfigurationValue");
619 r = read(fd, tmp, sizeof(tmp));
622 usbi_err(DEVICE_CTX(dev),
623 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
624 return LIBUSB_ERROR_IO;
626 usbi_dbg("device unconfigured");
631 if (tmp[sizeof(tmp) - 1] != 0) {
632 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
633 return LIBUSB_ERROR_IO;
634 } else if (tmp[0] == 0) {
635 usbi_err(DEVICE_CTX(dev), "no configuration value?");
636 return LIBUSB_ERROR_IO;
639 num = strtol(tmp, &endptr, 10);
641 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
642 return LIBUSB_ERROR_IO;
649 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
650 * seeks to the next one. */
651 static int seek_to_next_config(struct libusb_context *ctx, int fd,
654 struct libusb_config_descriptor config;
655 unsigned char tmp[6];
659 /* read first 6 bytes of descriptor */
660 r = read(fd, tmp, sizeof(tmp));
662 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
663 return LIBUSB_ERROR_IO;
664 } else if (r < sizeof(tmp)) {
665 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
666 return LIBUSB_ERROR_IO;
669 /* seek forward to end of config */
670 usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
671 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
673 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
674 return LIBUSB_ERROR_IO;
680 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
681 unsigned char *buffer, size_t len)
688 unsigned char tmp[6];
690 r = sysfs_get_active_config(dev, &config);
694 return LIBUSB_ERROR_NOT_FOUND;
696 usbi_dbg("active configuration %d", config);
698 /* sysfs provides access to an in-memory copy of the device descriptor,
699 * so we use that rather than keeping our own copy */
701 fd = _open_sysfs_attr(dev, "descriptors");
705 /* device might have been unconfigured since we read bConfigurationValue,
706 * so first check that there is any config descriptor data at all... */
707 off = lseek(fd, 0, SEEK_END);
709 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
712 return LIBUSB_ERROR_IO;
713 } else if (off == DEVICE_DESC_LENGTH) {
715 return LIBUSB_ERROR_NOT_FOUND;
718 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
720 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
722 return LIBUSB_ERROR_IO;
725 /* unbounded loop: we expect the descriptor to be present under all
728 r = read(fd, tmp, sizeof(tmp));
730 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
732 return LIBUSB_ERROR_IO;
733 } else if (r < sizeof(tmp)) {
734 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
735 return LIBUSB_ERROR_IO;
738 /* check bConfigurationValue */
739 if (tmp[5] == config)
742 /* try the next descriptor */
743 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
745 return LIBUSB_ERROR_IO;
747 r = seek_to_next_config(DEVICE_CTX(dev), fd, 0);
752 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
753 memcpy(buffer, tmp, to_copy);
754 if (len > sizeof(tmp)) {
755 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
757 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
761 usbi_dbg("device is unconfigured");
762 r = LIBUSB_ERROR_NOT_FOUND;
763 } else if (r < len - sizeof(tmp)) {
764 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
775 int linux_get_device_address (struct libusb_context *ctx, int detached,
776 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
777 const char *sys_name)
779 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
780 /* can't use sysfs to read the bus and device number if the
781 * device has been detached */
782 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
783 if (NULL == dev_node) {
784 return LIBUSB_ERROR_OTHER;
787 /* will this work with all supported kernel versions? */
788 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
789 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
790 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
791 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
794 return LIBUSB_SUCCESS;
797 usbi_dbg("scan %s", sys_name);
799 *busnum = __read_sysfs_attr(ctx, sys_name, "busnum");
803 *devaddr = __read_sysfs_attr(ctx, sys_name, "devnum");
807 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
808 if (*busnum > 255 || *devaddr > 255)
809 return LIBUSB_ERROR_INVALID_PARAM;
811 return LIBUSB_SUCCESS;
814 static int op_get_active_config_descriptor(struct libusb_device *dev,
815 unsigned char *buffer, size_t len, int *host_endian)
817 if (sysfs_has_descriptors) {
818 return sysfs_get_active_config_descriptor(dev, buffer, len);
820 return usbfs_get_active_config_descriptor(dev, buffer, len);
824 /* takes a usbfs fd, attempts to find the requested config and copy a certain
825 * amount of it into an output buffer. */
826 static int get_config_descriptor(struct libusb_context *ctx, int fd,
827 uint8_t config_index, unsigned char *buffer, size_t len)
832 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
834 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
835 return LIBUSB_ERROR_IO;
838 /* might need to skip some configuration descriptors to reach the
839 * requested configuration */
840 while (config_index > 0) {
841 r = seek_to_next_config(ctx, fd, 1);
847 /* read the rest of the descriptor */
848 r = read(fd, buffer, len);
850 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
851 return LIBUSB_ERROR_IO;
852 } else if (r < len) {
853 usbi_err(ctx, "short output read %d/%d", r, len);
859 static int op_get_config_descriptor(struct libusb_device *dev,
860 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
862 char filename[PATH_MAX];
866 /* always read from usbfs: sysfs only has the active descriptor
867 * this will involve waking the device up, but oh well! */
869 /* FIXME: the above is no longer true, new kernels have all descriptors
870 * in the descriptors file. but its kinda hard to detect if the kernel
871 * is sufficiently new. */
873 _get_usbfs_path(dev, filename);
874 fd = open(filename, O_RDONLY);
876 usbi_err(DEVICE_CTX(dev),
877 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
878 return LIBUSB_ERROR_IO;
881 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
886 /* cache the active config descriptor in memory. a value of -1 means that
887 * we aren't sure which one is active, so just assume the first one.
889 static int cache_active_config(struct libusb_device *dev, int fd,
892 struct linux_device_priv *priv = _device_priv(dev);
893 struct libusb_config_descriptor config;
894 unsigned char tmp[8];
899 if (active_config == -1) {
902 r = usbi_get_config_index_by_value(dev, active_config, &idx);
906 return LIBUSB_ERROR_NOT_FOUND;
909 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
911 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
915 usbi_parse_descriptor(tmp, "bbw", &config, 0);
916 buf = malloc(config.wTotalLength);
918 return LIBUSB_ERROR_NO_MEM;
920 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
921 config.wTotalLength);
927 if (priv->config_descriptor)
928 free(priv->config_descriptor);
929 priv->config_descriptor = buf;
933 /* send a control message to retrieve active configuration */
934 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
936 unsigned char active_config = 0;
939 struct usbfs_ctrltransfer ctrl = {
940 .bmRequestType = LIBUSB_ENDPOINT_IN,
941 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
946 .data = &active_config
949 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
952 return LIBUSB_ERROR_NO_DEVICE;
954 /* we hit this error path frequently with buggy devices :( */
955 usbi_warn(DEVICE_CTX(dev),
956 "get_configuration failed ret=%d errno=%d", r, errno);
957 return LIBUSB_ERROR_IO;
960 return active_config;
963 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
964 uint8_t devaddr, const char *sysfs_dir)
966 struct linux_device_priv *priv = _device_priv(dev);
967 unsigned char *dev_buf;
970 int active_config = 0;
971 int device_configured = 1;
974 dev->bus_number = busnum;
975 dev->device_address = devaddr;
978 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
979 if (!priv->sysfs_dir)
980 return LIBUSB_ERROR_NO_MEM;
981 strcpy(priv->sysfs_dir, sysfs_dir);
983 /* Note speed can contain 1.5, in this case __read_sysfs_attr
984 will stop parsing at the '.' and return 1 */
985 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
988 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
989 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
990 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
991 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
993 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
998 if (sysfs_has_descriptors)
1001 /* cache device descriptor in memory so that we can retrieve it later
1002 * without waking the device up (op_get_device_descriptor) */
1004 priv->dev_descriptor = NULL;
1005 priv->config_descriptor = NULL;
1007 if (sysfs_can_relate_devices) {
1008 int tmp = sysfs_get_active_config(dev, &active_config);
1011 if (active_config == -1)
1012 device_configured = 0;
1015 _get_usbfs_path(dev, path);
1016 fd = open(path, O_RDWR);
1017 if (fd < 0 && errno == EACCES) {
1018 fd = open(path, O_RDONLY);
1019 /* if we only have read-only access to the device, we cannot
1020 * send a control message to determine the active config. just
1021 * assume the first one is active. */
1026 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
1027 return LIBUSB_ERROR_IO;
1030 if (!sysfs_can_relate_devices) {
1031 if (active_config == -1) {
1032 /* if we only have read-only access to the device, we cannot
1033 * send a control message to determine the active config. just
1034 * assume the first one is active. */
1035 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
1036 "determine active configuration descriptor", path);
1038 active_config = usbfs_get_active_config(dev, fd);
1039 if (active_config == LIBUSB_ERROR_IO) {
1040 /* buggy devices sometimes fail to report their active config.
1041 * assume unconfigured and continue the probing */
1042 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
1043 "configuration, assumung unconfigured");
1044 device_configured = 0;
1045 } else if (active_config < 0) {
1047 return active_config;
1048 } else if (active_config == 0) {
1049 /* some buggy devices have a configuration 0, but we're
1050 * reaching into the corner of a corner case here, so let's
1051 * not support buggy devices in these circumstances.
1052 * stick to the specs: a configuration value of 0 means
1054 usbi_dbg("active cfg 0? assuming unconfigured device");
1055 device_configured = 0;
1060 dev_buf = malloc(DEVICE_DESC_LENGTH);
1063 return LIBUSB_ERROR_NO_MEM;
1066 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
1068 usbi_err(DEVICE_CTX(dev),
1069 "read descriptor failed ret=%d errno=%d", fd, errno);
1072 return LIBUSB_ERROR_IO;
1073 } else if (r < DEVICE_DESC_LENGTH) {
1074 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
1077 return LIBUSB_ERROR_IO;
1080 /* bit of a hack: set num_configurations now because cache_active_config()
1081 * calls usbi_get_config_index_by_value() which uses it */
1082 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
1084 if (device_configured) {
1085 r = cache_active_config(dev, fd, active_config);
1094 priv->dev_descriptor = dev_buf;
1098 static struct libusb_device *linux_parent_dev(struct libusb_context *ctx, const char *sysfs_dir)
1100 struct libusb_device *dev, *parent_dev = NULL;
1101 char *parent_sysfs_dir, *tmp;
1102 int ret, add_parent = 1;
1104 /* XXX -- can we figure out the topology when using usbfs? */
1105 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1106 /* either using usbfs or finding the parent of a root hub */
1110 parent_sysfs_dir = strdup(sysfs_dir);
1111 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1112 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1115 free (parent_sysfs_dir);
1116 /* shouldn't happen */
1120 /* is the parent a root hub? */
1121 if (NULL == strchr(parent_sysfs_dir, '-')) {
1122 tmp = parent_sysfs_dir;
1123 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1131 /* find the parent in the context */
1132 usbi_mutex_lock(&ctx->usb_devs_lock);
1133 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
1134 struct linux_device_priv *priv = _device_priv(dev);
1135 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1140 usbi_mutex_unlock(&ctx->usb_devs_lock);
1142 if (!parent_dev && add_parent) {
1143 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1145 sysfs_scan_device(ctx, parent_sysfs_dir);
1150 free (parent_sysfs_dir);
1154 int linux_enumerate_device(struct libusb_context *ctx,
1155 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1157 unsigned long session_id;
1158 struct libusb_device *dev;
1161 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1162 * will be reused. instead we should add a simple sysfs attribute with
1164 session_id = busnum << 8 | devaddr;
1165 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1168 if (usbi_get_device_by_session_id(ctx, session_id)) {
1169 /* device already exists in the context */
1170 usbi_dbg("session_id %ld already exists", session_id);
1171 return LIBUSB_SUCCESS;
1174 usbi_dbg("allocating new device for %d/%d (session %ld)",
1175 busnum, devaddr, session_id);
1176 dev = usbi_alloc_device(ctx, session_id);
1178 return LIBUSB_ERROR_NO_MEM;
1180 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1183 r = usbi_sanitize_device(dev);
1187 dev->parent_dev = linux_parent_dev(ctx, sysfs_dir);
1188 fprintf (stderr, "Dev %p (%s) has parent %p\n", dev, sysfs_dir,
1192 libusb_unref_device(dev);
1194 usbi_connect_device(dev);
1199 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1201 struct libusb_context *ctx;
1203 usbi_mutex_static_lock(&active_contexts_lock);
1204 usbi_mutex_static_lock(&hotplug_lock);
1205 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1206 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1208 usbi_mutex_static_unlock(&hotplug_lock);
1209 usbi_mutex_static_unlock(&active_contexts_lock);
1212 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1214 struct libusb_context *ctx;
1215 struct libusb_device *dev;
1217 usbi_mutex_static_lock(&active_contexts_lock);
1218 usbi_mutex_static_lock(&hotplug_lock);
1219 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1220 dev = usbi_get_device_by_session_id (ctx, busnum << 8 | devaddr);
1222 usbi_disconnect_device (dev);
1224 usbi_err(ctx, "device not found for session %x", busnum << 8 | devaddr);
1227 usbi_mutex_static_unlock(&hotplug_lock);
1228 usbi_mutex_static_unlock(&active_contexts_lock);
1231 #if !defined(USE_UDEV)
1232 /* open a bus directory and adds all discovered devices to the context */
1233 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1236 char dirpath[PATH_MAX];
1237 struct dirent *entry;
1238 int r = LIBUSB_ERROR_IO;
1240 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1241 usbi_dbg("%s", dirpath);
1242 dir = opendir(dirpath);
1244 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1245 /* FIXME: should handle valid race conditions like hub unplugged
1246 * during directory iteration - this is not an error */
1250 while ((entry = readdir(dir))) {
1253 if (entry->d_name[0] == '.')
1256 devaddr = atoi(entry->d_name);
1258 usbi_dbg("unknown dir entry %s", entry->d_name);
1262 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1263 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1274 static int usbfs_get_device_list(struct libusb_context *ctx)
1276 struct dirent *entry;
1277 DIR *buses = opendir(usbfs_path);
1281 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1282 return LIBUSB_ERROR_IO;
1285 while ((entry = readdir(buses))) {
1288 if (entry->d_name[0] == '.')
1293 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1296 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1298 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1302 busnum = atoi(entry->d_name);
1304 usbi_dbg("unknown dir entry %s", entry->d_name);
1308 r = usbfs_scan_busdir(ctx, busnum);
1320 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1322 uint8_t busnum, devaddr;
1325 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1326 if (LIBUSB_SUCCESS != ret) {
1330 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1334 #if !defined(USE_UDEV)
1335 static int sysfs_get_device_list(struct libusb_context *ctx)
1337 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1338 struct dirent *entry;
1339 int r = LIBUSB_ERROR_IO;
1342 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1346 while ((entry = readdir(devices))) {
1347 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1348 || strchr(entry->d_name, ':'))
1351 if (sysfs_scan_device(ctx, entry->d_name)) {
1352 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1363 static int linux_default_scan_devices (struct libusb_context *ctx)
1365 /* we can retrieve device list and descriptors from sysfs or usbfs.
1366 * sysfs is preferable, because if we use usbfs we end up resuming
1367 * any autosuspended USB devices. however, sysfs is not available
1368 * everywhere, so we need a usbfs fallback too.
1370 * as described in the "sysfs vs usbfs" comment at the top of this
1371 * file, sometimes we have sysfs but not enough information to
1372 * relate sysfs devices to usbfs nodes. op_init() determines the
1373 * adequacy of sysfs and sets sysfs_can_relate_devices.
1375 if (sysfs_can_relate_devices != 0)
1376 return sysfs_get_device_list(ctx);
1378 return usbfs_get_device_list(ctx);
1382 static int op_open(struct libusb_device_handle *handle)
1384 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1385 char filename[PATH_MAX];
1388 _get_usbfs_path(handle->dev, filename);
1389 usbi_dbg("opening %s", filename);
1390 hpriv->fd = open(filename, O_RDWR);
1391 if (hpriv->fd < 0) {
1392 if (errno == EACCES) {
1393 usbi_err(HANDLE_CTX(handle), "libusbx couldn't open USB device %s: "
1394 "Permission denied.", filename);
1395 usbi_err(HANDLE_CTX(handle),
1396 "libusbx requires write access to USB device nodes.");
1397 return LIBUSB_ERROR_ACCESS;
1398 } else if (errno == ENOENT) {
1399 usbi_err(HANDLE_CTX(handle), "libusbx couldn't open USB device %s: "
1400 "No such file or directory.", filename);
1401 return LIBUSB_ERROR_NO_DEVICE;
1403 usbi_err(HANDLE_CTX(handle),
1404 "open failed, code %d errno %d", hpriv->fd, errno);
1405 return LIBUSB_ERROR_IO;
1409 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1411 if (errno == ENOTTY)
1412 usbi_dbg("%s: getcap not available", filename);
1414 usbi_err(HANDLE_CTX(handle),
1415 "%s: getcap failed (%d)", filename, errno);
1417 if (supports_flag_zero_packet)
1418 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1419 if (supports_flag_bulk_continuation)
1420 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1423 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1426 static void op_close(struct libusb_device_handle *dev_handle)
1428 int fd = _device_handle_priv(dev_handle)->fd;
1429 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1433 static int op_get_configuration(struct libusb_device_handle *handle,
1437 if (sysfs_can_relate_devices != 1)
1438 return LIBUSB_ERROR_NOT_SUPPORTED;
1440 r = sysfs_get_active_config(handle->dev, config);
1444 if (*config == -1) {
1445 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1452 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1454 struct linux_device_priv *priv = _device_priv(handle->dev);
1455 int fd = _device_handle_priv(handle)->fd;
1456 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1458 if (errno == EINVAL)
1459 return LIBUSB_ERROR_NOT_FOUND;
1460 else if (errno == EBUSY)
1461 return LIBUSB_ERROR_BUSY;
1462 else if (errno == ENODEV)
1463 return LIBUSB_ERROR_NO_DEVICE;
1465 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1466 return LIBUSB_ERROR_OTHER;
1469 if (!sysfs_has_descriptors) {
1470 /* update our cached active config descriptor */
1472 if (priv->config_descriptor) {
1473 free(priv->config_descriptor);
1474 priv->config_descriptor = NULL;
1477 r = cache_active_config(handle->dev, fd, config);
1479 usbi_warn(HANDLE_CTX(handle),
1480 "failed to update cached config descriptor, error %d", r);
1487 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1489 int fd = _device_handle_priv(handle)->fd;
1490 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1492 if (errno == ENOENT)
1493 return LIBUSB_ERROR_NOT_FOUND;
1494 else if (errno == EBUSY)
1495 return LIBUSB_ERROR_BUSY;
1496 else if (errno == ENODEV)
1497 return LIBUSB_ERROR_NO_DEVICE;
1499 usbi_err(HANDLE_CTX(handle),
1500 "claim interface failed, error %d errno %d", r, errno);
1501 return LIBUSB_ERROR_OTHER;
1506 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1508 int fd = _device_handle_priv(handle)->fd;
1509 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1511 if (errno == ENODEV)
1512 return LIBUSB_ERROR_NO_DEVICE;
1514 usbi_err(HANDLE_CTX(handle),
1515 "release interface failed, error %d errno %d", r, errno);
1516 return LIBUSB_ERROR_OTHER;
1521 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1524 int fd = _device_handle_priv(handle)->fd;
1525 struct usbfs_setinterface setintf;
1528 setintf.interface = iface;
1529 setintf.altsetting = altsetting;
1530 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1532 if (errno == EINVAL)
1533 return LIBUSB_ERROR_NOT_FOUND;
1534 else if (errno == ENODEV)
1535 return LIBUSB_ERROR_NO_DEVICE;
1537 usbi_err(HANDLE_CTX(handle),
1538 "setintf failed error %d errno %d", r, errno);
1539 return LIBUSB_ERROR_OTHER;
1545 static int op_clear_halt(struct libusb_device_handle *handle,
1546 unsigned char endpoint)
1548 int fd = _device_handle_priv(handle)->fd;
1549 unsigned int _endpoint = endpoint;
1550 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1552 if (errno == ENOENT)
1553 return LIBUSB_ERROR_NOT_FOUND;
1554 else if (errno == ENODEV)
1555 return LIBUSB_ERROR_NO_DEVICE;
1557 usbi_err(HANDLE_CTX(handle),
1558 "clear_halt failed error %d errno %d", r, errno);
1559 return LIBUSB_ERROR_OTHER;
1565 static int op_reset_device(struct libusb_device_handle *handle)
1567 int fd = _device_handle_priv(handle)->fd;
1570 /* Doing a device reset will cause the usbfs driver to get unbound
1571 from any interfaces it is bound to. By voluntarily unbinding
1572 the usbfs driver ourself, we stop the kernel from rebinding
1573 the interface after reset (which would end up with the interface
1574 getting bound to the in kernel driver if any). */
1575 for (i = 0; i < USB_MAXINTERFACES; i++) {
1576 if (handle->claimed_interfaces & (1L << i)) {
1577 op_release_interface(handle, i);
1581 usbi_mutex_lock(&handle->lock);
1582 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1584 if (errno == ENODEV) {
1585 ret = LIBUSB_ERROR_NOT_FOUND;
1589 usbi_err(HANDLE_CTX(handle),
1590 "reset failed error %d errno %d", r, errno);
1591 ret = LIBUSB_ERROR_OTHER;
1595 /* And re-claim any interfaces which were claimed before the reset */
1596 for (i = 0; i < USB_MAXINTERFACES; i++) {
1597 if (handle->claimed_interfaces & (1L << i)) {
1598 r = op_claim_interface(handle, i);
1600 usbi_warn(HANDLE_CTX(handle),
1601 "failed to re-claim interface %d after reset", i);
1602 handle->claimed_interfaces &= ~(1L << i);
1607 usbi_mutex_unlock(&handle->lock);
1611 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1614 int fd = _device_handle_priv(handle)->fd;
1615 struct usbfs_getdriver getdrv;
1618 getdrv.interface = interface;
1619 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1621 if (errno == ENODATA)
1623 else if (errno == ENODEV)
1624 return LIBUSB_ERROR_NO_DEVICE;
1626 usbi_err(HANDLE_CTX(handle),
1627 "get driver failed error %d errno %d", r, errno);
1628 return LIBUSB_ERROR_OTHER;
1634 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1637 int fd = _device_handle_priv(handle)->fd;
1638 struct usbfs_ioctl command;
1639 struct usbfs_getdriver getdrv;
1642 command.ifno = interface;
1643 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1644 command.data = NULL;
1646 getdrv.interface = interface;
1647 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1648 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1649 return LIBUSB_ERROR_NOT_FOUND;
1651 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1653 if (errno == ENODATA)
1654 return LIBUSB_ERROR_NOT_FOUND;
1655 else if (errno == EINVAL)
1656 return LIBUSB_ERROR_INVALID_PARAM;
1657 else if (errno == ENODEV)
1658 return LIBUSB_ERROR_NO_DEVICE;
1660 usbi_err(HANDLE_CTX(handle),
1661 "detach failed error %d errno %d", r, errno);
1662 return LIBUSB_ERROR_OTHER;
1668 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1671 int fd = _device_handle_priv(handle)->fd;
1672 struct usbfs_ioctl command;
1675 command.ifno = interface;
1676 command.ioctl_code = IOCTL_USBFS_CONNECT;
1677 command.data = NULL;
1679 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1681 if (errno == ENODATA)
1682 return LIBUSB_ERROR_NOT_FOUND;
1683 else if (errno == EINVAL)
1684 return LIBUSB_ERROR_INVALID_PARAM;
1685 else if (errno == ENODEV)
1686 return LIBUSB_ERROR_NO_DEVICE;
1687 else if (errno == EBUSY)
1688 return LIBUSB_ERROR_BUSY;
1690 usbi_err(HANDLE_CTX(handle),
1691 "attach failed error %d errno %d", r, errno);
1692 return LIBUSB_ERROR_OTHER;
1693 } else if (r == 0) {
1694 return LIBUSB_ERROR_NOT_FOUND;
1700 static void op_destroy_device(struct libusb_device *dev)
1702 struct linux_device_priv *priv = _device_priv(dev);
1703 if (!sysfs_has_descriptors) {
1704 if (priv->dev_descriptor)
1705 free(priv->dev_descriptor);
1706 if (priv->config_descriptor)
1707 free(priv->config_descriptor);
1709 if (priv->sysfs_dir)
1710 free(priv->sysfs_dir);
1713 /* URBs are discarded in reverse order of submission to avoid races. */
1714 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1716 struct libusb_transfer *transfer =
1717 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1718 struct linux_transfer_priv *tpriv =
1719 usbi_transfer_get_os_priv(itransfer);
1720 struct linux_device_handle_priv *dpriv =
1721 _device_handle_priv(transfer->dev_handle);
1723 struct usbfs_urb *urb;
1725 for (i = last_plus_one - 1; i >= first; i--) {
1726 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1727 urb = tpriv->iso_urbs[i];
1729 urb = &tpriv->urbs[i];
1731 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1734 if (EINVAL == errno) {
1735 usbi_dbg("URB not found --> assuming ready to be reaped");
1736 if (i == (last_plus_one - 1))
1737 ret = LIBUSB_ERROR_NOT_FOUND;
1738 } else if (ENODEV == errno) {
1739 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1740 ret = LIBUSB_ERROR_NO_DEVICE;
1742 usbi_warn(TRANSFER_CTX(transfer),
1743 "unrecognised discard errno %d", errno);
1744 ret = LIBUSB_ERROR_OTHER;
1750 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1753 for (i = 0; i < tpriv->num_urbs; i++) {
1754 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1760 free(tpriv->iso_urbs);
1761 tpriv->iso_urbs = NULL;
1764 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1765 unsigned char urb_type)
1767 struct libusb_transfer *transfer =
1768 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1769 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1770 struct linux_device_handle_priv *dpriv =
1771 _device_handle_priv(transfer->dev_handle);
1772 struct usbfs_urb *urbs;
1773 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1774 == LIBUSB_ENDPOINT_OUT;
1775 int bulk_buffer_len, use_bulk_continuation;
1781 return LIBUSB_ERROR_BUSY;
1783 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1784 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1785 return LIBUSB_ERROR_NOT_SUPPORTED;
1788 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1789 * around this by splitting large transfers into 16k blocks, and then
1790 * submit all urbs at once. it would be simpler to submit one urb at
1791 * a time, but there is a big performance gain doing it this way.
1793 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1794 * using arbritary large transfers can still be a bad idea though, as
1795 * the kernel needs to allocate physical contiguous memory for this,
1796 * which may fail for large buffers.
1798 * The kernel solves this problem by splitting the transfer into
1799 * blocks itself when the host-controller is scatter-gather capable
1800 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1802 * Last, there is the issue of short-transfers when splitting, for
1803 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1804 * is needed, but this is not always available.
1806 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1807 /* Good! Just submit everything in one go */
1808 bulk_buffer_len = transfer->length ? transfer->length : 1;
1809 use_bulk_continuation = 0;
1810 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1811 /* Split the transfers and use bulk-continuation to
1812 avoid issues with short-transfers */
1813 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1814 use_bulk_continuation = 1;
1815 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1816 /* Don't split, assume the kernel can alloc the buffer
1817 (otherwise the submit will fail with -ENOMEM) */
1818 bulk_buffer_len = transfer->length ? transfer->length : 1;
1819 use_bulk_continuation = 0;
1821 /* Bad, splitting without bulk-continuation, short transfers
1822 which end before the last urb will not work reliable! */
1823 /* Note we don't warn here as this is "normal" on kernels <
1824 2.6.32 and not a problem for most applications */
1825 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1826 use_bulk_continuation = 0;
1829 int num_urbs = transfer->length / bulk_buffer_len;
1830 int last_urb_partial = 0;
1832 if (transfer->length == 0) {
1834 } else if ((transfer->length % bulk_buffer_len) > 0) {
1835 last_urb_partial = 1;
1838 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1840 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1841 urbs = calloc(1, alloc_size);
1843 return LIBUSB_ERROR_NO_MEM;
1845 tpriv->num_urbs = num_urbs;
1846 tpriv->num_retired = 0;
1847 tpriv->reap_action = NORMAL;
1848 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1850 for (i = 0; i < num_urbs; i++) {
1851 struct usbfs_urb *urb = &urbs[i];
1852 urb->usercontext = itransfer;
1853 urb->type = urb_type;
1854 urb->endpoint = transfer->endpoint;
1855 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1856 /* don't set the short not ok flag for the last URB */
1857 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1858 urb->flags = USBFS_URB_SHORT_NOT_OK;
1859 if (i == num_urbs - 1 && last_urb_partial)
1860 urb->buffer_length = transfer->length % bulk_buffer_len;
1861 else if (transfer->length == 0)
1862 urb->buffer_length = 0;
1864 urb->buffer_length = bulk_buffer_len;
1866 if (i > 0 && use_bulk_continuation)
1867 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1869 /* we have already checked that the flag is supported */
1870 if (is_out && i == num_urbs - 1 &&
1871 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1872 urb->flags |= USBFS_URB_ZERO_PACKET;
1874 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1876 if (errno == ENODEV) {
1877 r = LIBUSB_ERROR_NO_DEVICE;
1879 usbi_err(TRANSFER_CTX(transfer),
1880 "submiturb failed error %d errno=%d", r, errno);
1881 r = LIBUSB_ERROR_IO;
1884 /* if the first URB submission fails, we can simply free up and
1885 * return failure immediately. */
1887 usbi_dbg("first URB failed, easy peasy");
1893 /* if it's not the first URB that failed, the situation is a bit
1894 * tricky. we may need to discard all previous URBs. there are
1896 * - discarding is asynchronous - discarded urbs will be reaped
1897 * later. the user must not have freed the transfer when the
1898 * discarded URBs are reaped, otherwise libusbx will be using
1900 * - the earlier URBs may have completed successfully and we do
1901 * not want to throw away any data.
1902 * - this URB failing may be no error; EREMOTEIO means that
1903 * this transfer simply didn't need all the URBs we submitted
1904 * so, we report that the transfer was submitted successfully and
1905 * in case of error we discard all previous URBs. later when
1906 * the final reap completes we can report error to the user,
1907 * or success if an earlier URB was completed successfully.
1909 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1911 /* The URBs we haven't submitted yet we count as already
1913 tpriv->num_retired += num_urbs - i;
1915 /* If we completed short then don't try to discard. */
1916 if (COMPLETED_EARLY == tpriv->reap_action)
1919 discard_urbs(itransfer, 0, i);
1921 usbi_dbg("reporting successful submission but waiting for %d "
1922 "discards before reporting error", i);
1930 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1932 struct libusb_transfer *transfer =
1933 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1934 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1935 struct linux_device_handle_priv *dpriv =
1936 _device_handle_priv(transfer->dev_handle);
1937 struct usbfs_urb **urbs;
1939 int num_packets = transfer->num_iso_packets;
1941 int this_urb_len = 0;
1943 int packet_offset = 0;
1944 unsigned int packet_len;
1945 unsigned char *urb_buffer = transfer->buffer;
1947 if (tpriv->iso_urbs)
1948 return LIBUSB_ERROR_BUSY;
1950 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1951 * into smaller units to meet such restriction, then fire off all the
1952 * units at once. it would be simpler if we just fired one unit at a time,
1953 * but there is a big performance gain through doing it this way.
1955 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1956 * using arbritary large transfers is still be a bad idea though, as
1957 * the kernel needs to allocate physical contiguous memory for this,
1958 * which may fail for large buffers.
1961 /* calculate how many URBs we need */
1962 for (i = 0; i < num_packets; i++) {
1963 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1964 packet_len = transfer->iso_packet_desc[i].length;
1966 if (packet_len > space_remaining) {
1968 this_urb_len = packet_len;
1970 this_urb_len += packet_len;
1973 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1975 alloc_size = num_urbs * sizeof(*urbs);
1976 urbs = calloc(1, alloc_size);
1978 return LIBUSB_ERROR_NO_MEM;
1980 tpriv->iso_urbs = urbs;
1981 tpriv->num_urbs = num_urbs;
1982 tpriv->num_retired = 0;
1983 tpriv->reap_action = NORMAL;
1984 tpriv->iso_packet_offset = 0;
1986 /* allocate + initialize each URB with the correct number of packets */
1987 for (i = 0; i < num_urbs; i++) {
1988 struct usbfs_urb *urb;
1989 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1990 int urb_packet_offset = 0;
1991 unsigned char *urb_buffer_orig = urb_buffer;
1995 /* swallow up all the packets we can fit into this URB */
1996 while (packet_offset < transfer->num_iso_packets) {
1997 packet_len = transfer->iso_packet_desc[packet_offset].length;
1998 if (packet_len <= space_remaining_in_urb) {
2000 urb_packet_offset++;
2002 space_remaining_in_urb -= packet_len;
2003 urb_buffer += packet_len;
2005 /* it can't fit, save it for the next URB */
2010 alloc_size = sizeof(*urb)
2011 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2012 urb = calloc(1, alloc_size);
2014 free_iso_urbs(tpriv);
2015 return LIBUSB_ERROR_NO_MEM;
2019 /* populate packet lengths */
2020 for (j = 0, k = packet_offset - urb_packet_offset;
2021 k < packet_offset; k++, j++) {
2022 packet_len = transfer->iso_packet_desc[k].length;
2023 urb->iso_frame_desc[j].length = packet_len;
2026 urb->usercontext = itransfer;
2027 urb->type = USBFS_URB_TYPE_ISO;
2028 /* FIXME: interface for non-ASAP data? */
2029 urb->flags = USBFS_URB_ISO_ASAP;
2030 urb->endpoint = transfer->endpoint;
2031 urb->number_of_packets = urb_packet_offset;
2032 urb->buffer = urb_buffer_orig;
2036 for (i = 0; i < num_urbs; i++) {
2037 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2039 if (errno == ENODEV) {
2040 r = LIBUSB_ERROR_NO_DEVICE;
2042 usbi_err(TRANSFER_CTX(transfer),
2043 "submiturb failed error %d errno=%d", r, errno);
2044 r = LIBUSB_ERROR_IO;
2047 /* if the first URB submission fails, we can simply free up and
2048 * return failure immediately. */
2050 usbi_dbg("first URB failed, easy peasy");
2051 free_iso_urbs(tpriv);
2055 /* if it's not the first URB that failed, the situation is a bit
2056 * tricky. we must discard all previous URBs. there are
2058 * - discarding is asynchronous - discarded urbs will be reaped
2059 * later. the user must not have freed the transfer when the
2060 * discarded URBs are reaped, otherwise libusbx will be using
2062 * - the earlier URBs may have completed successfully and we do
2063 * not want to throw away any data.
2064 * so, in this case we discard all the previous URBs BUT we report
2065 * that the transfer was submitted successfully. then later when
2066 * the final discard completes we can report error to the user.
2068 tpriv->reap_action = SUBMIT_FAILED;
2070 /* The URBs we haven't submitted yet we count as already
2072 tpriv->num_retired = num_urbs - i;
2073 discard_urbs(itransfer, 0, i);
2075 usbi_dbg("reporting successful submission but waiting for %d "
2076 "discards before reporting error", i);
2084 static int submit_control_transfer(struct usbi_transfer *itransfer)
2086 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2087 struct libusb_transfer *transfer =
2088 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2089 struct linux_device_handle_priv *dpriv =
2090 _device_handle_priv(transfer->dev_handle);
2091 struct usbfs_urb *urb;
2095 return LIBUSB_ERROR_BUSY;
2097 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2098 return LIBUSB_ERROR_INVALID_PARAM;
2100 urb = calloc(1, sizeof(struct usbfs_urb));
2102 return LIBUSB_ERROR_NO_MEM;
2104 tpriv->num_urbs = 1;
2105 tpriv->reap_action = NORMAL;
2107 urb->usercontext = itransfer;
2108 urb->type = USBFS_URB_TYPE_CONTROL;
2109 urb->endpoint = transfer->endpoint;
2110 urb->buffer = transfer->buffer;
2111 urb->buffer_length = transfer->length;
2113 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2117 if (errno == ENODEV)
2118 return LIBUSB_ERROR_NO_DEVICE;
2120 usbi_err(TRANSFER_CTX(transfer),
2121 "submiturb failed error %d errno=%d", r, errno);
2122 return LIBUSB_ERROR_IO;
2127 static int op_submit_transfer(struct usbi_transfer *itransfer)
2129 struct libusb_transfer *transfer =
2130 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2132 switch (transfer->type) {
2133 case LIBUSB_TRANSFER_TYPE_CONTROL:
2134 return submit_control_transfer(itransfer);
2135 case LIBUSB_TRANSFER_TYPE_BULK:
2136 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2137 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2138 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2139 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2140 return submit_iso_transfer(itransfer);
2142 usbi_err(TRANSFER_CTX(transfer),
2143 "unknown endpoint type %d", transfer->type);
2144 return LIBUSB_ERROR_INVALID_PARAM;
2148 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2150 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2151 struct libusb_transfer *transfer =
2152 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2154 switch (transfer->type) {
2155 case LIBUSB_TRANSFER_TYPE_BULK:
2156 if (tpriv->reap_action == ERROR)
2158 /* else, fall through */
2159 case LIBUSB_TRANSFER_TYPE_CONTROL:
2160 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2161 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2162 tpriv->reap_action = CANCELLED;
2165 usbi_err(TRANSFER_CTX(transfer),
2166 "unknown endpoint type %d", transfer->type);
2167 return LIBUSB_ERROR_INVALID_PARAM;
2171 return LIBUSB_ERROR_NOT_FOUND;
2173 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2176 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2178 struct libusb_transfer *transfer =
2179 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2180 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2182 /* urbs can be freed also in submit_transfer so lock mutex first */
2183 switch (transfer->type) {
2184 case LIBUSB_TRANSFER_TYPE_CONTROL:
2185 case LIBUSB_TRANSFER_TYPE_BULK:
2186 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2187 usbi_mutex_lock(&itransfer->lock);
2191 usbi_mutex_unlock(&itransfer->lock);
2193 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2194 usbi_mutex_lock(&itransfer->lock);
2195 if (tpriv->iso_urbs)
2196 free_iso_urbs(tpriv);
2197 usbi_mutex_unlock(&itransfer->lock);
2200 usbi_err(TRANSFER_CTX(transfer),
2201 "unknown endpoint type %d", transfer->type);
2205 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2206 struct usbfs_urb *urb)
2208 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2209 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2210 int urb_idx = urb - tpriv->urbs;
2212 usbi_mutex_lock(&itransfer->lock);
2213 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2214 urb_idx + 1, tpriv->num_urbs);
2216 tpriv->num_retired++;
2218 if (tpriv->reap_action != NORMAL) {
2219 /* cancelled, submit_fail, or completed early */
2220 usbi_dbg("abnormal reap: urb status %d", urb->status);
2222 /* even though we're in the process of cancelling, it's possible that
2223 * we may receive some data in these URBs that we don't want to lose.
2225 * 1. while the kernel is cancelling all the packets that make up an
2226 * URB, a few of them might complete. so we get back a successful
2227 * cancellation *and* some data.
2228 * 2. we receive a short URB which marks the early completion condition,
2229 * so we start cancelling the remaining URBs. however, we're too
2230 * slow and another URB completes (or at least completes partially).
2231 * (this can't happen since we always use BULK_CONTINUATION.)
2233 * When this happens, our objectives are not to lose any "surplus" data,
2234 * and also to stick it at the end of the previously-received data
2235 * (closing any holes), so that libusbx reports the total amount of
2236 * transferred data and presents it in a contiguous chunk.
2238 if (urb->actual_length > 0) {
2239 unsigned char *target = transfer->buffer + itransfer->transferred;
2240 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2241 if (urb->buffer != target) {
2242 usbi_dbg("moving surplus data from offset %d to offset %d",
2243 (unsigned char *) urb->buffer - transfer->buffer,
2244 target - transfer->buffer);
2245 memmove(target, urb->buffer, urb->actual_length);
2247 itransfer->transferred += urb->actual_length;
2250 if (tpriv->num_retired == tpriv->num_urbs) {
2251 usbi_dbg("abnormal reap: last URB handled, reporting");
2252 if (tpriv->reap_action != COMPLETED_EARLY &&
2253 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2254 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2260 itransfer->transferred += urb->actual_length;
2262 /* Many of these errors can occur on *any* urb of a multi-urb
2263 * transfer. When they do, we tear down the rest of the transfer.
2265 switch (urb->status) {
2268 case -EREMOTEIO: /* short transfer */
2270 case -ENOENT: /* cancelled */
2275 usbi_dbg("device removed");
2276 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2277 goto cancel_remaining;
2279 usbi_dbg("detected endpoint stall");
2280 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2281 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2282 goto cancel_remaining;
2284 /* overflow can only ever occur in the last urb */
2285 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2286 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2287 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2294 usbi_dbg("low level error %d", urb->status);
2295 tpriv->reap_action = ERROR;
2296 goto cancel_remaining;
2298 usbi_warn(ITRANSFER_CTX(itransfer),
2299 "unrecognised urb status %d", urb->status);
2300 tpriv->reap_action = ERROR;
2301 goto cancel_remaining;
2304 /* if we're the last urb or we got less data than requested then we're
2306 if (urb_idx == tpriv->num_urbs - 1) {
2307 usbi_dbg("last URB in transfer --> complete!");
2309 } else if (urb->actual_length < urb->buffer_length) {
2310 usbi_dbg("short transfer %d/%d --> complete!",
2311 urb->actual_length, urb->buffer_length);
2312 if (tpriv->reap_action == NORMAL)
2313 tpriv->reap_action = COMPLETED_EARLY;
2318 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2319 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2321 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2324 /* cancel remaining urbs and wait for their completion before
2325 * reporting results */
2326 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2329 usbi_mutex_unlock(&itransfer->lock);
2335 usbi_mutex_unlock(&itransfer->lock);
2336 return CANCELLED == tpriv->reap_action ?
2337 usbi_handle_transfer_cancellation(itransfer) :
2338 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2341 static int handle_iso_completion(struct usbi_transfer *itransfer,
2342 struct usbfs_urb *urb)
2344 struct libusb_transfer *transfer =
2345 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2346 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2347 int num_urbs = tpriv->num_urbs;
2350 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2352 usbi_mutex_lock(&itransfer->lock);
2353 for (i = 0; i < num_urbs; i++) {
2354 if (urb == tpriv->iso_urbs[i]) {
2360 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2361 usbi_mutex_unlock(&itransfer->lock);
2362 return LIBUSB_ERROR_NOT_FOUND;
2365 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2368 /* copy isochronous results back in */
2370 for (i = 0; i < urb->number_of_packets; i++) {
2371 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2372 struct libusb_iso_packet_descriptor *lib_desc =
2373 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2374 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2375 switch (urb_desc->status) {
2378 case -ENOENT: /* cancelled */
2383 usbi_dbg("device removed");
2384 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2387 usbi_dbg("detected endpoint stall");
2388 lib_desc->status = LIBUSB_TRANSFER_STALL;
2391 usbi_dbg("overflow error");
2392 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2400 usbi_dbg("low-level USB error %d", urb_desc->status);
2401 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2404 usbi_warn(TRANSFER_CTX(transfer),
2405 "unrecognised urb status %d", urb_desc->status);
2406 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2409 lib_desc->actual_length = urb_desc->actual_length;
2412 tpriv->num_retired++;
2414 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2415 usbi_dbg("CANCEL: urb status %d", urb->status);
2417 if (tpriv->num_retired == num_urbs) {
2418 usbi_dbg("CANCEL: last URB handled, reporting");
2419 free_iso_urbs(tpriv);
2420 if (tpriv->reap_action == CANCELLED) {
2421 usbi_mutex_unlock(&itransfer->lock);
2422 return usbi_handle_transfer_cancellation(itransfer);
2424 usbi_mutex_unlock(&itransfer->lock);
2425 return usbi_handle_transfer_completion(itransfer,
2426 LIBUSB_TRANSFER_ERROR);
2432 switch (urb->status) {
2435 case -ENOENT: /* cancelled */
2439 usbi_dbg("device removed");
2440 status = LIBUSB_TRANSFER_NO_DEVICE;
2443 usbi_warn(TRANSFER_CTX(transfer),
2444 "unrecognised urb status %d", urb->status);
2445 status = LIBUSB_TRANSFER_ERROR;
2449 /* if we're the last urb then we're done */
2450 if (urb_idx == num_urbs) {
2451 usbi_dbg("last URB in transfer --> complete!");
2452 free_iso_urbs(tpriv);
2453 usbi_mutex_unlock(&itransfer->lock);
2454 return usbi_handle_transfer_completion(itransfer, status);
2458 usbi_mutex_unlock(&itransfer->lock);
2462 static int handle_control_completion(struct usbi_transfer *itransfer,
2463 struct usbfs_urb *urb)
2465 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2468 usbi_mutex_lock(&itransfer->lock);
2469 usbi_dbg("handling completion status %d", urb->status);
2471 itransfer->transferred += urb->actual_length;
2473 if (tpriv->reap_action == CANCELLED) {
2474 if (urb->status != 0 && urb->status != -ENOENT)
2475 usbi_warn(ITRANSFER_CTX(itransfer),
2476 "cancel: unrecognised urb status %d", urb->status);
2479 usbi_mutex_unlock(&itransfer->lock);
2480 return usbi_handle_transfer_cancellation(itransfer);
2483 switch (urb->status) {
2485 status = LIBUSB_TRANSFER_COMPLETED;
2487 case -ENOENT: /* cancelled */
2488 status = LIBUSB_TRANSFER_CANCELLED;
2492 usbi_dbg("device removed");
2493 status = LIBUSB_TRANSFER_NO_DEVICE;
2496 usbi_dbg("unsupported control request");
2497 status = LIBUSB_TRANSFER_STALL;
2500 usbi_dbg("control overflow error");
2501 status = LIBUSB_TRANSFER_OVERFLOW;
2508 usbi_dbg("low-level bus error occurred");
2509 status = LIBUSB_TRANSFER_ERROR;
2512 usbi_warn(ITRANSFER_CTX(itransfer),
2513 "unrecognised urb status %d", urb->status);
2514 status = LIBUSB_TRANSFER_ERROR;
2520 usbi_mutex_unlock(&itransfer->lock);
2521 return usbi_handle_transfer_completion(itransfer, status);
2524 static int reap_for_handle(struct libusb_device_handle *handle)
2526 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2528 struct usbfs_urb *urb;
2529 struct usbi_transfer *itransfer;
2530 struct libusb_transfer *transfer;
2532 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2533 if (r == -1 && errno == EAGAIN)
2536 if (errno == ENODEV)
2537 return LIBUSB_ERROR_NO_DEVICE;
2539 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2541 return LIBUSB_ERROR_IO;
2544 itransfer = urb->usercontext;
2545 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2547 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2548 urb->actual_length);
2550 switch (transfer->type) {
2551 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2552 return handle_iso_completion(itransfer, urb);
2553 case LIBUSB_TRANSFER_TYPE_BULK:
2554 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2555 return handle_bulk_completion(itransfer, urb);
2556 case LIBUSB_TRANSFER_TYPE_CONTROL:
2557 return handle_control_completion(itransfer, urb);
2559 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2561 return LIBUSB_ERROR_OTHER;
2565 static int op_handle_events(struct libusb_context *ctx,
2566 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2571 usbi_mutex_lock(&ctx->open_devs_lock);
2572 for (i = 0; i < nfds && num_ready > 0; i++) {
2573 struct pollfd *pollfd = &fds[i];
2574 struct libusb_device_handle *handle;
2575 struct linux_device_handle_priv *hpriv = NULL;
2577 if (!pollfd->revents)
2581 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2582 hpriv = _device_handle_priv(handle);
2583 if (hpriv->fd == pollfd->fd)
2587 if (pollfd->revents & POLLERR) {
2588 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2589 usbi_handle_disconnect(handle);
2594 r = reap_for_handle(handle);
2596 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2604 usbi_mutex_unlock(&ctx->open_devs_lock);
2608 static int op_clock_gettime(int clk_id, struct timespec *tp)
2611 case USBI_CLOCK_MONOTONIC:
2612 return clock_gettime(monotonic_clkid, tp);
2613 case USBI_CLOCK_REALTIME:
2614 return clock_gettime(CLOCK_REALTIME, tp);
2616 return LIBUSB_ERROR_INVALID_PARAM;
2620 #ifdef USBI_TIMERFD_AVAILABLE
2621 static clockid_t op_get_timerfd_clockid(void)
2623 return monotonic_clkid;
2628 const struct usbi_os_backend linux_usbfs_backend = {
2629 .name = "Linux usbfs",
2630 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2633 .get_device_list = NULL,
2634 .get_device_descriptor = op_get_device_descriptor,
2635 .get_active_config_descriptor = op_get_active_config_descriptor,
2636 .get_config_descriptor = op_get_config_descriptor,
2640 .get_configuration = op_get_configuration,
2641 .set_configuration = op_set_configuration,
2642 .claim_interface = op_claim_interface,
2643 .release_interface = op_release_interface,
2645 .set_interface_altsetting = op_set_interface,
2646 .clear_halt = op_clear_halt,
2647 .reset_device = op_reset_device,
2649 .kernel_driver_active = op_kernel_driver_active,
2650 .detach_kernel_driver = op_detach_kernel_driver,
2651 .attach_kernel_driver = op_attach_kernel_driver,
2653 .destroy_device = op_destroy_device,
2655 .submit_transfer = op_submit_transfer,
2656 .cancel_transfer = op_cancel_transfer,
2657 .clear_transfer_priv = op_clear_transfer_priv,
2659 .handle_events = op_handle_events,
2661 .clock_gettime = op_clock_gettime,
2663 #ifdef USBI_TIMERFD_AVAILABLE
2664 .get_timerfd_clockid = op_get_timerfd_clockid,
2667 .device_priv_size = sizeof(struct linux_device_priv),
2668 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2669 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2670 .add_iso_packet_size = 0,