2 * Linux usbfs backend for libusb
3 * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * 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 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
76 * allows us to mark URBs as being part of a specific logical transfer when
77 * we submit them to the kernel. then, on any error except a cancellation, all
78 * URBs within that transfer will be cancelled and no more URBs will be
79 * accepted for the transfer, meaning that no more data can creep in.
81 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
82 * (in either direction) except the first.
83 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
84 * last; it means that the kernel should treat a short reply as an error.
85 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
86 * transfers can't be short unless there's already some sort of error), and
87 * setting this flag is disallowed (a kernel with USB debugging enabled will
90 static int supports_flag_bulk_continuation = -1;
92 /* clock ID for monotonic clock, as not all clock sources are available on all
93 * systems. appropriate choice made at initialization time. */
94 static clockid_t monotonic_clkid = -1;
96 /* do we have a busnum to relate devices? this also implies that we can read
97 * the active configuration through bConfigurationValue */
98 static int sysfs_can_relate_devices = -1;
100 /* do we have a descriptors file? */
101 static int sysfs_has_descriptors = -1;
103 struct linux_device_priv {
105 unsigned char *dev_descriptor;
106 unsigned char *config_descriptor;
109 struct linux_device_handle_priv {
115 /* submission failed after the first URB, so await cancellation/completion
116 * of all the others */
119 /* cancelled by user or timeout */
122 /* completed multi-URB transfer in non-final URB */
125 /* one or more urbs encountered a low-level error */
129 struct linux_transfer_priv {
131 struct usbfs_urb *urbs;
132 struct usbfs_urb **iso_urbs;
135 enum reap_action reap_action;
137 unsigned int num_retired;
138 enum libusb_transfer_status reap_status;
140 /* next iso packet in user-supplied transfer to be populated */
141 int iso_packet_offset;
144 static void __get_usbfs_path(struct libusb_device *dev, char *path)
146 snprintf(path, PATH_MAX, "%s/%03d/%03d", usbfs_path, dev->bus_number,
147 dev->device_address);
150 static struct linux_device_priv *__device_priv(struct libusb_device *dev)
152 return (struct linux_device_priv *) dev->os_priv;
155 static struct linux_device_handle_priv *__device_handle_priv(
156 struct libusb_device_handle *handle)
158 return (struct linux_device_handle_priv *) handle->os_priv;
161 static int check_usb_vfs(const char *dirname)
164 struct dirent *entry;
167 dir = opendir(dirname);
171 while ((entry = readdir(dir)) != NULL) {
172 if (entry->d_name[0] == '.')
175 /* We assume if we find any files that it must be the right place */
184 static const char *find_usbfs_path(void)
186 const char *path = "/dev/bus/usb";
187 const char *ret = NULL;
189 if (check_usb_vfs(path)) {
192 path = "/proc/bus/usb";
193 if (check_usb_vfs(path))
197 usbi_dbg("found usbfs at %s", ret);
201 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
202 * seem to lack it). fall back to REALTIME if we have to. */
203 static clockid_t find_monotonic_clock(void)
208 #ifdef CLOCK_MONOTONIC
209 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
210 * because it's not available through timerfd */
211 r = clock_gettime(CLOCK_MONOTONIC, &ts);
213 return CLOCK_MONOTONIC;
214 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
217 return CLOCK_REALTIME;
220 /* bulk continuation URB flag available from Linux 2.6.32 */
221 static int check_flag_bulk_continuation(void)
224 int major, minor, sublevel;
228 if (strlen(uts.release) < 4)
230 if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &sublevel) != 3)
245 static int op_init(struct libusb_context *ctx)
250 usbfs_path = find_usbfs_path();
252 usbi_err(ctx, "could not find usbfs");
253 return LIBUSB_ERROR_OTHER;
256 if (monotonic_clkid == -1)
257 monotonic_clkid = find_monotonic_clock();
259 if (supports_flag_bulk_continuation == -1) {
260 supports_flag_bulk_continuation = check_flag_bulk_continuation();
261 if (supports_flag_bulk_continuation == -1) {
262 usbi_err(ctx, "error checking for bulk continuation support");
263 return LIBUSB_ERROR_OTHER;
267 if (supports_flag_bulk_continuation)
268 usbi_dbg("bulk continuation flag supported");
270 r = stat(SYSFS_DEVICE_PATH, &statbuf);
271 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
272 usbi_dbg("found usb devices in sysfs");
274 usbi_dbg("sysfs usb info not available");
275 sysfs_has_descriptors = 0;
276 sysfs_can_relate_devices = 0;
282 static int usbfs_get_device_descriptor(struct libusb_device *dev,
283 unsigned char *buffer)
285 struct linux_device_priv *priv = __device_priv(dev);
287 /* return cached copy */
288 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
292 static int __open_sysfs_attr(struct libusb_device *dev, const char *attr)
294 struct linux_device_priv *priv = __device_priv(dev);
295 char filename[PATH_MAX];
298 snprintf(filename, PATH_MAX, "%s/%s/%s",
299 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
300 fd = open(filename, O_RDONLY);
302 usbi_err(DEVICE_CTX(dev),
303 "open %s failed ret=%d errno=%d", filename, fd, errno);
304 return LIBUSB_ERROR_IO;
310 static int sysfs_get_device_descriptor(struct libusb_device *dev,
311 unsigned char *buffer)
316 /* sysfs provides access to an in-memory copy of the device descriptor,
317 * so we use that rather than keeping our own copy */
319 fd = __open_sysfs_attr(dev, "descriptors");
323 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
326 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
327 return LIBUSB_ERROR_IO;
328 } else if (r < DEVICE_DESC_LENGTH) {
329 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
330 return LIBUSB_ERROR_IO;
336 static int op_get_device_descriptor(struct libusb_device *dev,
337 unsigned char *buffer, int *host_endian)
339 if (sysfs_has_descriptors) {
340 return sysfs_get_device_descriptor(dev, buffer);
343 return usbfs_get_device_descriptor(dev, buffer);
347 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
348 unsigned char *buffer, size_t len)
350 struct linux_device_priv *priv = __device_priv(dev);
351 if (!priv->config_descriptor)
352 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
354 /* retrieve cached copy */
355 memcpy(buffer, priv->config_descriptor, len);
359 /* read the bConfigurationValue for a device */
360 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
363 char tmp[4] = {0, 0, 0, 0};
368 fd = __open_sysfs_attr(dev, "bConfigurationValue");
372 r = read(fd, tmp, sizeof(tmp));
375 usbi_err(DEVICE_CTX(dev),
376 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
377 return LIBUSB_ERROR_IO;
379 usbi_err(DEVICE_CTX(dev), "device unconfigured");
384 if (tmp[sizeof(tmp) - 1] != 0) {
385 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
386 return LIBUSB_ERROR_IO;
387 } else if (tmp[0] == 0) {
388 usbi_err(DEVICE_CTX(dev), "no configuration value?");
389 return LIBUSB_ERROR_IO;
392 num = strtol(tmp, &endptr, 10);
394 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
395 return LIBUSB_ERROR_IO;
402 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
403 * seeks to the next one. */
404 static int seek_to_next_config(struct libusb_context *ctx, int fd,
407 struct libusb_config_descriptor config;
408 unsigned char tmp[6];
412 /* read first 6 bytes of descriptor */
413 r = read(fd, tmp, sizeof(tmp));
415 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
416 return LIBUSB_ERROR_IO;
417 } else if (r < sizeof(tmp)) {
418 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
419 return LIBUSB_ERROR_IO;
422 /* seek forward to end of config */
423 usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
424 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
426 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
427 return LIBUSB_ERROR_IO;
433 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
434 unsigned char *buffer, size_t len)
441 unsigned char tmp[6];
443 r = sysfs_get_active_config(dev, &config);
447 return LIBUSB_ERROR_NOT_FOUND;
449 usbi_dbg("active configuration %d", config);
451 /* sysfs provides access to an in-memory copy of the device descriptor,
452 * so we use that rather than keeping our own copy */
454 fd = __open_sysfs_attr(dev, "descriptors");
458 /* device might have been unconfigured since we read bConfigurationValue,
459 * so first check that there is any config descriptor data at all... */
460 off = lseek(fd, 0, SEEK_END);
462 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
465 return LIBUSB_ERROR_IO;
466 } else if (off == DEVICE_DESC_LENGTH) {
468 return LIBUSB_ERROR_NOT_FOUND;
471 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
473 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
475 return LIBUSB_ERROR_IO;
478 /* unbounded loop: we expect the descriptor to be present under all
481 r = read(fd, tmp, sizeof(tmp));
483 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
485 return LIBUSB_ERROR_IO;
486 } else if (r < sizeof(tmp)) {
487 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
488 return LIBUSB_ERROR_IO;
491 /* check bConfigurationValue */
492 if (tmp[5] == config)
495 /* try the next descriptor */
496 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
498 return LIBUSB_ERROR_IO;
500 r = seek_to_next_config(DEVICE_CTX(dev), fd, 0);
505 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
506 memcpy(buffer, tmp, to_copy);
507 if (len > sizeof(tmp)) {
508 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
510 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
514 usbi_dbg("device is unconfigured");
515 r = LIBUSB_ERROR_NOT_FOUND;
516 } else if (r < len - sizeof(tmp)) {
517 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
528 static int op_get_active_config_descriptor(struct libusb_device *dev,
529 unsigned char *buffer, size_t len, int *host_endian)
531 if (sysfs_has_descriptors) {
532 return sysfs_get_active_config_descriptor(dev, buffer, len);
534 return usbfs_get_active_config_descriptor(dev, buffer, len);
538 /* takes a usbfs fd, attempts to find the requested config and copy a certain
539 * amount of it into an output buffer. */
540 static int get_config_descriptor(struct libusb_context *ctx, int fd,
541 uint8_t config_index, unsigned char *buffer, size_t len)
546 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
548 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
549 return LIBUSB_ERROR_IO;
552 /* might need to skip some configuration descriptors to reach the
553 * requested configuration */
554 while (config_index > 0) {
555 r = seek_to_next_config(ctx, fd, 1);
561 /* read the rest of the descriptor */
562 r = read(fd, buffer, len);
564 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
565 return LIBUSB_ERROR_IO;
566 } else if (r < len) {
567 usbi_err(ctx, "short output read %d/%d", r, len);
568 return LIBUSB_ERROR_IO;
574 static int op_get_config_descriptor(struct libusb_device *dev,
575 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
577 char filename[PATH_MAX];
581 /* always read from usbfs: sysfs only has the active descriptor
582 * this will involve waking the device up, but oh well! */
584 /* FIXME: the above is no longer true, new kernels have all descriptors
585 * in the descriptors file. but its kinda hard to detect if the kernel
586 * is sufficiently new. */
588 __get_usbfs_path(dev, filename);
589 fd = open(filename, O_RDONLY);
591 usbi_err(DEVICE_CTX(dev),
592 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
593 return LIBUSB_ERROR_IO;
596 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
601 /* cache the active config descriptor in memory. a value of -1 means that
602 * we aren't sure which one is active, so just assume the first one.
604 static int cache_active_config(struct libusb_device *dev, int fd,
607 struct linux_device_priv *priv = __device_priv(dev);
608 struct libusb_config_descriptor config;
609 unsigned char tmp[8];
614 if (active_config == -1) {
617 r = usbi_get_config_index_by_value(dev, active_config, &idx);
621 return LIBUSB_ERROR_NOT_FOUND;
624 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
626 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
630 usbi_parse_descriptor(tmp, "bbw", &config, 0);
631 buf = malloc(config.wTotalLength);
633 return LIBUSB_ERROR_NO_MEM;
635 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
636 config.wTotalLength);
642 if (priv->config_descriptor)
643 free(priv->config_descriptor);
644 priv->config_descriptor = buf;
648 /* send a control message to retrieve active configuration */
649 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
651 unsigned char active_config = 0;
654 struct usbfs_ctrltransfer ctrl = {
655 .bmRequestType = LIBUSB_ENDPOINT_IN,
656 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
661 .data = &active_config
664 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
667 return LIBUSB_ERROR_NO_DEVICE;
669 /* we hit this error path frequently with buggy devices :( */
670 usbi_warn(DEVICE_CTX(dev),
671 "get_configuration failed ret=%d errno=%d", r, errno);
672 return LIBUSB_ERROR_IO;
675 return active_config;
678 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
679 uint8_t devaddr, const char *sysfs_dir)
681 struct linux_device_priv *priv = __device_priv(dev);
682 unsigned char *dev_buf;
685 int active_config = 0;
686 int device_configured = 1;
689 dev->bus_number = busnum;
690 dev->device_address = devaddr;
693 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
694 if (!priv->sysfs_dir)
695 return LIBUSB_ERROR_NO_MEM;
696 strcpy(priv->sysfs_dir, sysfs_dir);
699 if (sysfs_has_descriptors)
702 /* cache device descriptor in memory so that we can retrieve it later
703 * without waking the device up (op_get_device_descriptor) */
705 priv->dev_descriptor = NULL;
706 priv->config_descriptor = NULL;
708 if (sysfs_can_relate_devices) {
709 int tmp = sysfs_get_active_config(dev, &active_config);
712 if (active_config == -1)
713 device_configured = 0;
716 __get_usbfs_path(dev, path);
717 fd = open(path, O_RDWR);
718 if (fd < 0 && errno == EACCES) {
719 fd = open(path, O_RDONLY);
720 /* if we only have read-only access to the device, we cannot
721 * send a control message to determine the active config. just
722 * assume the first one is active. */
727 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
728 return LIBUSB_ERROR_IO;
731 if (!sysfs_can_relate_devices) {
732 if (active_config == -1) {
733 /* if we only have read-only access to the device, we cannot
734 * send a control message to determine the active config. just
735 * assume the first one is active. */
736 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
737 "determine active configuration descriptor", path);
739 active_config = usbfs_get_active_config(dev, fd);
740 if (active_config == LIBUSB_ERROR_IO) {
741 /* buggy devices sometimes fail to report their active config.
742 * assume unconfigured and continue the probing */
743 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
744 "configuration, assumung unconfigured");
745 device_configured = 0;
746 } else if (active_config < 0) {
748 return active_config;
749 } else if (active_config == 0) {
750 /* some buggy devices have a configuration 0, but we're
751 * reaching into the corner of a corner case here, so let's
752 * not support buggy devices in these circumstances.
753 * stick to the specs: a configuration value of 0 means
755 usbi_dbg("active cfg 0? assuming unconfigured device");
756 device_configured = 0;
761 dev_buf = malloc(DEVICE_DESC_LENGTH);
764 return LIBUSB_ERROR_NO_MEM;
767 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
769 usbi_err(DEVICE_CTX(dev),
770 "read descriptor failed ret=%d errno=%d", fd, errno);
773 return LIBUSB_ERROR_IO;
774 } else if (r < DEVICE_DESC_LENGTH) {
775 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
778 return LIBUSB_ERROR_IO;
781 /* bit of a hack: set num_configurations now because cache_active_config()
782 * calls usbi_get_config_index_by_value() which uses it */
783 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
785 if (device_configured) {
786 r = cache_active_config(dev, fd, active_config);
795 priv->dev_descriptor = dev_buf;
799 static int enumerate_device(struct libusb_context *ctx,
800 struct discovered_devs **_discdevs, uint8_t busnum, uint8_t devaddr,
801 const char *sysfs_dir)
803 struct discovered_devs *discdevs;
804 unsigned long session_id;
806 struct libusb_device *dev;
809 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
810 * will be reused. instead we should add a simple sysfs attribute with
812 session_id = busnum << 8 | devaddr;
813 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
816 dev = usbi_get_device_by_session_id(ctx, session_id);
818 usbi_dbg("using existing device for %d/%d (session %ld)",
819 busnum, devaddr, session_id);
821 usbi_dbg("allocating new device for %d/%d (session %ld)",
822 busnum, devaddr, session_id);
823 dev = usbi_alloc_device(ctx, session_id);
825 return LIBUSB_ERROR_NO_MEM;
827 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
830 r = usbi_sanitize_device(dev);
835 discdevs = discovered_devs_append(*_discdevs, dev);
837 r = LIBUSB_ERROR_NO_MEM;
839 *_discdevs = discdevs;
843 libusb_unref_device(dev);
847 /* open a bus directory and adds all discovered devices to discdevs. on
848 * failure (non-zero return) the pre-existing discdevs should be destroyed
849 * (and devices freed). on success, the new discdevs pointer should be used
850 * as it may have been moved. */
851 static int usbfs_scan_busdir(struct libusb_context *ctx,
852 struct discovered_devs **_discdevs, uint8_t busnum)
855 char dirpath[PATH_MAX];
856 struct dirent *entry;
857 struct discovered_devs *discdevs = *_discdevs;
860 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
861 usbi_dbg("%s", dirpath);
862 dir = opendir(dirpath);
864 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
865 /* FIXME: should handle valid race conditions like hub unplugged
866 * during directory iteration - this is not an error */
867 return LIBUSB_ERROR_IO;
870 while ((entry = readdir(dir))) {
873 if (entry->d_name[0] == '.')
876 devaddr = atoi(entry->d_name);
878 usbi_dbg("unknown dir entry %s", entry->d_name);
882 r = enumerate_device(ctx, &discdevs, busnum, (uint8_t) devaddr, NULL);
887 *_discdevs = discdevs;
893 static int usbfs_get_device_list(struct libusb_context *ctx,
894 struct discovered_devs **_discdevs)
896 struct dirent *entry;
897 DIR *buses = opendir(usbfs_path);
898 struct discovered_devs *discdevs = *_discdevs;
902 usbi_err(ctx, "opendir buses failed errno=%d", errno);
903 return LIBUSB_ERROR_IO;
906 while ((entry = readdir(buses))) {
907 struct discovered_devs *discdevs_new = discdevs;
910 if (entry->d_name[0] == '.')
913 busnum = atoi(entry->d_name);
915 usbi_dbg("unknown dir entry %s", entry->d_name);
919 r = usbfs_scan_busdir(ctx, &discdevs_new, busnum);
922 discdevs = discdevs_new;
927 *_discdevs = discdevs;
932 static int sysfs_scan_device(struct libusb_context *ctx,
933 struct discovered_devs **_discdevs, const char *devname,
938 char filename[PATH_MAX];
942 usbi_dbg("scan %s", devname);
944 /* determine descriptors presence ahead of time, we need to know this
945 * when we reach initialize_device */
946 if (sysfs_has_descriptors == -1) {
949 snprintf(filename, PATH_MAX, "%s/%s/descriptors", SYSFS_DEVICE_PATH,
951 r = stat(filename, &statbuf);
952 if (r == 0 && S_ISREG(statbuf.st_mode)) {
953 usbi_dbg("sysfs descriptors available");
954 sysfs_has_descriptors = 1;
956 usbi_dbg("sysfs descriptors not available");
957 sysfs_has_descriptors = 0;
961 snprintf(filename, PATH_MAX, "%s/%s/busnum", SYSFS_DEVICE_PATH, devname);
962 fd = fopen(filename, "r");
964 if (errno == ENOENT) {
965 usbi_dbg("busnum not found, cannot relate sysfs to usbfs, "
966 "falling back on pure usbfs");
967 sysfs_can_relate_devices = 0;
969 return LIBUSB_ERROR_OTHER;
971 usbi_err(ctx, "open busnum failed, errno=%d", errno);
972 return LIBUSB_ERROR_IO;
975 sysfs_can_relate_devices = 1;
977 r = fscanf(fd, "%d", &busnum);
980 usbi_err(ctx, "fscanf busnum returned %d, errno=%d", r, errno);
981 return LIBUSB_ERROR_IO;
984 snprintf(filename, PATH_MAX, "%s/%s/devnum", SYSFS_DEVICE_PATH, devname);
985 fd = fopen(filename, "r");
987 usbi_err(ctx, "open devnum failed, errno=%d", errno);
988 return LIBUSB_ERROR_IO;
991 r = fscanf(fd, "%d", &devaddr);
994 usbi_err(ctx, "fscanf devnum returned %d, errno=%d", r, errno);
995 return LIBUSB_ERROR_IO;
998 usbi_dbg("bus=%d dev=%d", busnum, devaddr);
999 if (busnum > 255 || devaddr > 255)
1000 return LIBUSB_ERROR_INVALID_PARAM;
1002 return enumerate_device(ctx, _discdevs, busnum & 0xff, devaddr & 0xff,
1006 static int sysfs_get_device_list(struct libusb_context *ctx,
1007 struct discovered_devs **_discdevs, int *usbfs_fallback)
1009 struct discovered_devs *discdevs = *_discdevs;
1010 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1011 struct dirent *entry;
1015 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1016 return LIBUSB_ERROR_IO;
1019 while ((entry = readdir(devices))) {
1020 struct discovered_devs *discdevs_new = discdevs;
1022 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1023 || strchr(entry->d_name, ':'))
1026 r = sysfs_scan_device(ctx, &discdevs_new, entry->d_name,
1030 discdevs = discdevs_new;
1035 *_discdevs = discdevs;
1039 static int op_get_device_list(struct libusb_context *ctx,
1040 struct discovered_devs **_discdevs)
1042 /* we can retrieve device list and descriptors from sysfs or usbfs.
1043 * sysfs is preferable, because if we use usbfs we end up resuming
1044 * any autosuspended USB devices. however, sysfs is not available
1045 * everywhere, so we need a usbfs fallback too.
1047 * as described in the "sysfs vs usbfs" comment, sometimes we have
1048 * sysfs but not enough information to relate sysfs devices to usbfs
1049 * nodes. the usbfs_fallback variable is used to indicate that we should
1050 * fall back on usbfs.
1052 if (sysfs_can_relate_devices != 0) {
1053 int usbfs_fallback = 0;
1054 int r = sysfs_get_device_list(ctx, _discdevs, &usbfs_fallback);
1055 if (!usbfs_fallback)
1059 return usbfs_get_device_list(ctx, _discdevs);
1062 static int op_open(struct libusb_device_handle *handle)
1064 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
1065 char filename[PATH_MAX];
1067 __get_usbfs_path(handle->dev, filename);
1068 hpriv->fd = open(filename, O_RDWR);
1069 if (hpriv->fd < 0) {
1070 if (errno == EACCES) {
1071 usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
1072 "Permission denied.", filename);
1073 usbi_err(HANDLE_CTX(handle),
1074 "libusb requires write access to USB device nodes.");
1075 return LIBUSB_ERROR_ACCESS;
1076 } else if (errno == ENOENT) {
1077 return LIBUSB_ERROR_NO_DEVICE;
1079 usbi_err(HANDLE_CTX(handle),
1080 "open failed, code %d errno %d", hpriv->fd, errno);
1081 return LIBUSB_ERROR_IO;
1085 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1088 static void op_close(struct libusb_device_handle *dev_handle)
1090 int fd = __device_handle_priv(dev_handle)->fd;
1091 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1095 static int op_get_configuration(struct libusb_device_handle *handle,
1099 if (sysfs_can_relate_devices != 1)
1100 return LIBUSB_ERROR_NOT_SUPPORTED;
1102 r = sysfs_get_active_config(handle->dev, config);
1109 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1111 struct linux_device_priv *priv = __device_priv(handle->dev);
1112 int fd = __device_handle_priv(handle)->fd;
1113 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1115 if (errno == EINVAL)
1116 return LIBUSB_ERROR_NOT_FOUND;
1117 else if (errno == EBUSY)
1118 return LIBUSB_ERROR_BUSY;
1119 else if (errno == ENODEV)
1120 return LIBUSB_ERROR_NO_DEVICE;
1122 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1123 return LIBUSB_ERROR_OTHER;
1126 if (!sysfs_has_descriptors) {
1127 /* update our cached active config descriptor */
1129 if (priv->config_descriptor) {
1130 free(priv->config_descriptor);
1131 priv->config_descriptor = NULL;
1134 r = cache_active_config(handle->dev, fd, config);
1136 usbi_warn(HANDLE_CTX(handle),
1137 "failed to update cached config descriptor, error %d", r);
1144 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1146 int fd = __device_handle_priv(handle)->fd;
1147 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1149 if (errno == ENOENT)
1150 return LIBUSB_ERROR_NOT_FOUND;
1151 else if (errno == EBUSY)
1152 return LIBUSB_ERROR_BUSY;
1153 else if (errno == ENODEV)
1154 return LIBUSB_ERROR_NO_DEVICE;
1156 usbi_err(HANDLE_CTX(handle),
1157 "claim interface failed, error %d errno %d", r, errno);
1158 return LIBUSB_ERROR_OTHER;
1163 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1165 int fd = __device_handle_priv(handle)->fd;
1166 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1168 if (errno == ENODEV)
1169 return LIBUSB_ERROR_NO_DEVICE;
1171 usbi_err(HANDLE_CTX(handle),
1172 "release interface failed, error %d errno %d", r, errno);
1173 return LIBUSB_ERROR_OTHER;
1178 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1181 int fd = __device_handle_priv(handle)->fd;
1182 struct usbfs_setinterface setintf;
1185 setintf.interface = iface;
1186 setintf.altsetting = altsetting;
1187 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1189 if (errno == EINVAL)
1190 return LIBUSB_ERROR_NOT_FOUND;
1191 else if (errno == ENODEV)
1192 return LIBUSB_ERROR_NO_DEVICE;
1194 usbi_err(HANDLE_CTX(handle),
1195 "setintf failed error %d errno %d", r, errno);
1196 return LIBUSB_ERROR_OTHER;
1202 static int op_clear_halt(struct libusb_device_handle *handle,
1203 unsigned char endpoint)
1205 int fd = __device_handle_priv(handle)->fd;
1206 unsigned int _endpoint = endpoint;
1207 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1209 if (errno == ENOENT)
1210 return LIBUSB_ERROR_NOT_FOUND;
1211 else if (errno == ENODEV)
1212 return LIBUSB_ERROR_NO_DEVICE;
1214 usbi_err(HANDLE_CTX(handle),
1215 "clear_halt failed error %d errno %d", r, errno);
1216 return LIBUSB_ERROR_OTHER;
1222 static int op_reset_device(struct libusb_device_handle *handle)
1224 int fd = __device_handle_priv(handle)->fd;
1225 int r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1227 if (errno == ENODEV)
1228 return LIBUSB_ERROR_NOT_FOUND;
1230 usbi_err(HANDLE_CTX(handle),
1231 "reset failed error %d errno %d", r, errno);
1232 return LIBUSB_ERROR_OTHER;
1238 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1241 int fd = __device_handle_priv(handle)->fd;
1242 struct usbfs_getdriver getdrv;
1245 getdrv.interface = interface;
1246 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1248 if (errno == ENODATA)
1250 else if (errno == ENODEV)
1251 return LIBUSB_ERROR_NO_DEVICE;
1253 usbi_err(HANDLE_CTX(handle),
1254 "get driver failed error %d errno %d", r, errno);
1255 return LIBUSB_ERROR_OTHER;
1261 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1264 int fd = __device_handle_priv(handle)->fd;
1265 struct usbfs_ioctl command;
1268 command.ifno = interface;
1269 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1270 command.data = NULL;
1272 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1274 if (errno == ENODATA)
1275 return LIBUSB_ERROR_NOT_FOUND;
1276 else if (errno == EINVAL)
1277 return LIBUSB_ERROR_INVALID_PARAM;
1278 else if (errno == ENODEV)
1279 return LIBUSB_ERROR_NO_DEVICE;
1281 usbi_err(HANDLE_CTX(handle),
1282 "detach failed error %d errno %d", r, errno);
1283 return LIBUSB_ERROR_OTHER;
1289 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1292 int fd = __device_handle_priv(handle)->fd;
1293 struct usbfs_ioctl command;
1296 command.ifno = interface;
1297 command.ioctl_code = IOCTL_USBFS_CONNECT;
1298 command.data = NULL;
1300 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1302 if (errno == ENODATA)
1303 return LIBUSB_ERROR_NOT_FOUND;
1304 else if (errno == EINVAL)
1305 return LIBUSB_ERROR_INVALID_PARAM;
1306 else if (errno == ENODEV)
1307 return LIBUSB_ERROR_NO_DEVICE;
1308 else if (errno == EBUSY)
1309 return LIBUSB_ERROR_BUSY;
1311 usbi_err(HANDLE_CTX(handle),
1312 "attach failed error %d errno %d", r, errno);
1313 return LIBUSB_ERROR_OTHER;
1314 } else if (r == 0) {
1315 return LIBUSB_ERROR_NOT_FOUND;
1321 static void op_destroy_device(struct libusb_device *dev)
1323 struct linux_device_priv *priv = __device_priv(dev);
1324 if (!sysfs_has_descriptors) {
1325 if (priv->dev_descriptor)
1326 free(priv->dev_descriptor);
1327 if (priv->config_descriptor)
1328 free(priv->config_descriptor);
1330 if (priv->sysfs_dir)
1331 free(priv->sysfs_dir);
1334 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1337 for (i = 0; i < tpriv->num_urbs; i++) {
1338 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1344 free(tpriv->iso_urbs);
1345 tpriv->iso_urbs = NULL;
1348 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1349 unsigned char urb_type)
1351 struct libusb_transfer *transfer =
1352 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1353 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1354 struct linux_device_handle_priv *dpriv =
1355 __device_handle_priv(transfer->dev_handle);
1356 struct usbfs_urb *urbs;
1357 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1358 == LIBUSB_ENDPOINT_OUT;
1364 return LIBUSB_ERROR_BUSY;
1366 /* usbfs places a 16kb limit on bulk URBs. we divide up larger requests
1367 * into smaller units to meet such restriction, then fire off all the
1368 * units at once. it would be simpler if we just fired one unit at a time,
1369 * but there is a big performance gain through doing it this way. */
1370 int num_urbs = transfer->length / MAX_BULK_BUFFER_LENGTH;
1371 int last_urb_partial = 0;
1373 if (transfer->length == 0) {
1375 } else if ((transfer->length % MAX_BULK_BUFFER_LENGTH) > 0) {
1376 last_urb_partial = 1;
1379 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1381 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1382 urbs = malloc(alloc_size);
1384 return LIBUSB_ERROR_NO_MEM;
1385 memset(urbs, 0, alloc_size);
1387 tpriv->num_urbs = num_urbs;
1388 tpriv->num_retired = 0;
1389 tpriv->reap_action = NORMAL;
1390 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1392 for (i = 0; i < num_urbs; i++) {
1393 struct usbfs_urb *urb = &urbs[i];
1394 urb->usercontext = itransfer;
1395 urb->type = urb_type;
1396 urb->endpoint = transfer->endpoint;
1397 urb->buffer = transfer->buffer + (i * MAX_BULK_BUFFER_LENGTH);
1398 if (supports_flag_bulk_continuation && !is_out)
1399 urb->flags = USBFS_URB_SHORT_NOT_OK;
1400 if (i == num_urbs - 1 && last_urb_partial)
1401 urb->buffer_length = transfer->length % MAX_BULK_BUFFER_LENGTH;
1402 else if (transfer->length == 0)
1403 urb->buffer_length = 0;
1405 urb->buffer_length = MAX_BULK_BUFFER_LENGTH;
1407 if (i > 0 && supports_flag_bulk_continuation)
1408 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1410 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1414 if (errno == ENODEV) {
1415 r = LIBUSB_ERROR_NO_DEVICE;
1417 usbi_err(TRANSFER_CTX(transfer),
1418 "submiturb failed error %d errno=%d", r, errno);
1419 r = LIBUSB_ERROR_IO;
1422 /* if the first URB submission fails, we can simply free up and
1423 * return failure immediately. */
1425 usbi_dbg("first URB failed, easy peasy");
1431 /* if it's not the first URB that failed, the situation is a bit
1432 * tricky. we may need to discard all previous URBs. there are
1434 * - discarding is asynchronous - discarded urbs will be reaped
1435 * later. the user must not have freed the transfer when the
1436 * discarded URBs are reaped, otherwise libusb will be using
1438 * - the earlier URBs may have completed successfully and we do
1439 * not want to throw away any data.
1440 * - this URB failing may be no error; EREMOTEIO means that
1441 * this transfer simply didn't need all the URBs we submitted
1442 * so, we report that the transfer was submitted successfully and
1443 * in case of error we discard all previous URBs. later when
1444 * the final reap completes we can report error to the user,
1445 * or success if an earlier URB was completed successfully.
1447 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1449 /* The URBs we haven't submitted yet we count as already
1451 tpriv->num_retired += num_urbs - i;
1453 /* If we completed short then don't try to discard. */
1454 if (COMPLETED_EARLY == tpriv->reap_action)
1457 /* The URBs are discarded in reverse order of
1458 * submission, to avoid races. */
1459 for (j = i - 1; j >= 0; j--) {
1460 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &urbs[j]);
1461 if (tmp && errno != EINVAL)
1462 usbi_warn(TRANSFER_CTX(transfer),
1463 "unrecognised discard errno %d", errno);
1466 usbi_dbg("reporting successful submission but waiting for %d "
1467 "discards before reporting error", i);
1475 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1477 struct libusb_transfer *transfer =
1478 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1479 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1480 struct linux_device_handle_priv *dpriv =
1481 __device_handle_priv(transfer->dev_handle);
1482 struct usbfs_urb **urbs;
1484 int num_packets = transfer->num_iso_packets;
1486 int this_urb_len = 0;
1488 int packet_offset = 0;
1489 unsigned int packet_len;
1490 unsigned char *urb_buffer = transfer->buffer;
1492 if (tpriv->iso_urbs)
1493 return LIBUSB_ERROR_BUSY;
1495 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1496 * into smaller units to meet such restriction, then fire off all the
1497 * units at once. it would be simpler if we just fired one unit at a time,
1498 * but there is a big performance gain through doing it this way. */
1500 /* calculate how many URBs we need */
1501 for (i = 0; i < num_packets; i++) {
1502 int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1503 packet_len = transfer->iso_packet_desc[i].length;
1505 if (packet_len > space_remaining) {
1507 this_urb_len = packet_len;
1509 this_urb_len += packet_len;
1512 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1514 alloc_size = num_urbs * sizeof(*urbs);
1515 urbs = malloc(alloc_size);
1517 return LIBUSB_ERROR_NO_MEM;
1518 memset(urbs, 0, alloc_size);
1520 tpriv->iso_urbs = urbs;
1521 tpriv->num_urbs = num_urbs;
1522 tpriv->num_retired = 0;
1523 tpriv->reap_action = NORMAL;
1524 tpriv->iso_packet_offset = 0;
1526 /* allocate + initialize each URB with the correct number of packets */
1527 for (i = 0; i < num_urbs; i++) {
1528 struct usbfs_urb *urb;
1529 int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1530 int urb_packet_offset = 0;
1531 unsigned char *urb_buffer_orig = urb_buffer;
1535 /* swallow up all the packets we can fit into this URB */
1536 while (packet_offset < transfer->num_iso_packets) {
1537 packet_len = transfer->iso_packet_desc[packet_offset].length;
1538 if (packet_len <= space_remaining_in_urb) {
1540 urb_packet_offset++;
1542 space_remaining_in_urb -= packet_len;
1543 urb_buffer += packet_len;
1545 /* it can't fit, save it for the next URB */
1550 alloc_size = sizeof(*urb)
1551 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1552 urb = malloc(alloc_size);
1554 free_iso_urbs(tpriv);
1555 return LIBUSB_ERROR_NO_MEM;
1557 memset(urb, 0, alloc_size);
1560 /* populate packet lengths */
1561 for (j = 0, k = packet_offset - urb_packet_offset;
1562 k < packet_offset; k++, j++) {
1563 packet_len = transfer->iso_packet_desc[k].length;
1564 urb->iso_frame_desc[j].length = packet_len;
1567 urb->usercontext = itransfer;
1568 urb->type = USBFS_URB_TYPE_ISO;
1569 /* FIXME: interface for non-ASAP data? */
1570 urb->flags = USBFS_URB_ISO_ASAP;
1571 urb->endpoint = transfer->endpoint;
1572 urb->number_of_packets = urb_packet_offset;
1573 urb->buffer = urb_buffer_orig;
1577 for (i = 0; i < num_urbs; i++) {
1578 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1582 if (errno == ENODEV) {
1583 r = LIBUSB_ERROR_NO_DEVICE;
1585 usbi_err(TRANSFER_CTX(transfer),
1586 "submiturb failed error %d errno=%d", r, errno);
1587 r = LIBUSB_ERROR_IO;
1590 /* if the first URB submission fails, we can simply free up and
1591 * return failure immediately. */
1593 usbi_dbg("first URB failed, easy peasy");
1594 free_iso_urbs(tpriv);
1598 /* if it's not the first URB that failed, the situation is a bit
1599 * tricky. we must discard all previous URBs. there are
1601 * - discarding is asynchronous - discarded urbs will be reaped
1602 * later. the user must not have freed the transfer when the
1603 * discarded URBs are reaped, otherwise libusb will be using
1605 * - the earlier URBs may have completed successfully and we do
1606 * not want to throw away any data.
1607 * so, in this case we discard all the previous URBs BUT we report
1608 * that the transfer was submitted successfully. then later when
1609 * the final discard completes we can report error to the user.
1611 tpriv->reap_action = SUBMIT_FAILED;
1613 /* The URBs we haven't submitted yet we count as already
1615 tpriv->num_retired = num_urbs - i;
1616 for (j = i - 1; j >= 0; j--) {
1617 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urbs[j]);
1618 if (tmp && errno != EINVAL)
1619 usbi_warn(TRANSFER_CTX(transfer),
1620 "unrecognised discard errno %d", errno);
1623 usbi_dbg("reporting successful submission but waiting for %d "
1624 "discards before reporting error", i);
1632 static int submit_control_transfer(struct usbi_transfer *itransfer)
1634 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1635 struct libusb_transfer *transfer =
1636 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1637 struct linux_device_handle_priv *dpriv =
1638 __device_handle_priv(transfer->dev_handle);
1639 struct usbfs_urb *urb;
1643 return LIBUSB_ERROR_BUSY;
1645 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1646 return LIBUSB_ERROR_INVALID_PARAM;
1648 urb = malloc(sizeof(struct usbfs_urb));
1650 return LIBUSB_ERROR_NO_MEM;
1651 memset(urb, 0, sizeof(struct usbfs_urb));
1653 tpriv->reap_action = NORMAL;
1655 urb->usercontext = itransfer;
1656 urb->type = USBFS_URB_TYPE_CONTROL;
1657 urb->endpoint = transfer->endpoint;
1658 urb->buffer = transfer->buffer;
1659 urb->buffer_length = transfer->length;
1661 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1665 if (errno == ENODEV)
1666 return LIBUSB_ERROR_NO_DEVICE;
1668 usbi_err(TRANSFER_CTX(transfer),
1669 "submiturb failed error %d errno=%d", r, errno);
1670 return LIBUSB_ERROR_IO;
1675 static int op_submit_transfer(struct usbi_transfer *itransfer)
1677 struct libusb_transfer *transfer =
1678 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1680 switch (transfer->type) {
1681 case LIBUSB_TRANSFER_TYPE_CONTROL:
1682 return submit_control_transfer(itransfer);
1683 case LIBUSB_TRANSFER_TYPE_BULK:
1684 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1685 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1686 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1687 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1688 return submit_iso_transfer(itransfer);
1690 usbi_err(TRANSFER_CTX(transfer),
1691 "unknown endpoint type %d", transfer->type);
1692 return LIBUSB_ERROR_INVALID_PARAM;
1696 static int cancel_control_transfer(struct usbi_transfer *itransfer)
1698 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1699 struct libusb_transfer *transfer =
1700 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1701 struct linux_device_handle_priv *dpriv =
1702 __device_handle_priv(transfer->dev_handle);
1706 return LIBUSB_ERROR_NOT_FOUND;
1708 tpriv->reap_action = CANCELLED;
1709 r = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->urbs);
1711 if (errno == EINVAL) {
1712 usbi_dbg("URB not found --> assuming ready to be reaped");
1715 usbi_err(TRANSFER_CTX(transfer),
1716 "unrecognised DISCARD code %d", errno);
1717 return LIBUSB_ERROR_OTHER;
1724 static int cancel_bulk_transfer(struct usbi_transfer *itransfer)
1726 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1727 struct libusb_transfer *transfer =
1728 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1729 struct linux_device_handle_priv *dpriv =
1730 __device_handle_priv(transfer->dev_handle);
1734 return LIBUSB_ERROR_NOT_FOUND;
1736 if (tpriv->reap_action != ERROR)
1737 tpriv->reap_action = CANCELLED;
1739 for (i = tpriv->num_urbs - 1; i >= 0; i--) {
1740 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1741 if (tmp && errno != EINVAL)
1742 usbi_warn(TRANSFER_CTX(transfer),
1743 "unrecognised discard errno %d", errno);
1748 static int cancel_iso_transfer(struct usbi_transfer *itransfer)
1750 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1751 struct libusb_transfer *transfer =
1752 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1753 struct linux_device_handle_priv *dpriv =
1754 __device_handle_priv(transfer->dev_handle);
1757 if (!tpriv->iso_urbs)
1758 return LIBUSB_ERROR_NOT_FOUND;
1760 tpriv->reap_action = CANCELLED;
1761 for (i = tpriv->num_urbs - 1; i >= 0; i--) {
1762 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->iso_urbs[i]);
1763 if (tmp && errno != EINVAL)
1764 usbi_warn(TRANSFER_CTX(transfer),
1765 "unrecognised discard errno %d", errno);
1770 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1772 struct libusb_transfer *transfer =
1773 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1775 switch (transfer->type) {
1776 case LIBUSB_TRANSFER_TYPE_CONTROL:
1777 return cancel_control_transfer(itransfer);
1778 case LIBUSB_TRANSFER_TYPE_BULK:
1779 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1780 return cancel_bulk_transfer(itransfer);
1781 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1782 return cancel_iso_transfer(itransfer);
1784 usbi_err(TRANSFER_CTX(transfer),
1785 "unknown endpoint type %d", transfer->type);
1786 return LIBUSB_ERROR_INVALID_PARAM;
1790 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1792 struct libusb_transfer *transfer =
1793 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1794 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1796 switch (transfer->type) {
1797 case LIBUSB_TRANSFER_TYPE_CONTROL:
1798 case LIBUSB_TRANSFER_TYPE_BULK:
1799 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1803 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1804 free_iso_urbs(tpriv);
1807 usbi_err(TRANSFER_CTX(transfer),
1808 "unknown endpoint type %d", transfer->type);
1812 static int handle_bulk_completion(struct usbi_transfer *itransfer,
1813 struct usbfs_urb *urb)
1815 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1816 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1817 struct linux_device_handle_priv *dpriv = __device_handle_priv(transfer->dev_handle);
1818 int urb_idx = urb - tpriv->urbs;
1820 usbi_mutex_lock(&itransfer->lock);
1821 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1822 urb_idx + 1, tpriv->num_urbs);
1824 tpriv->num_retired++;
1826 if (tpriv->reap_action != NORMAL) {
1827 /* cancelled, submit_fail, or completed early */
1828 usbi_dbg("abnormal reap: urb status %d", urb->status);
1830 /* even though we're in the process of cancelling, it's possible that
1831 * we may receive some data in these URBs that we don't want to lose.
1833 * 1. while the kernel is cancelling all the packets that make up an
1834 * URB, a few of them might complete. so we get back a successful
1835 * cancellation *and* some data.
1836 * 2. we receive a short URB which marks the early completion condition,
1837 * so we start cancelling the remaining URBs. however, we're too
1838 * slow and another URB completes (or at least completes partially).
1839 * (this can't happen since we always use BULK_CONTINUATION.)
1841 * When this happens, our objectives are not to lose any "surplus" data,
1842 * and also to stick it at the end of the previously-received data
1843 * (closing any holes), so that libusb reports the total amount of
1844 * transferred data and presents it in a contiguous chunk.
1846 if (urb->actual_length > 0) {
1847 unsigned char *target = transfer->buffer + itransfer->transferred;
1848 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
1849 if (urb->buffer != target) {
1850 usbi_dbg("moving surplus data from offset %d to offset %d",
1851 (unsigned char *) urb->buffer - transfer->buffer,
1852 target - transfer->buffer);
1853 memmove(target, urb->buffer, urb->actual_length);
1855 itransfer->transferred += urb->actual_length;
1858 if (tpriv->num_retired == tpriv->num_urbs) {
1859 usbi_dbg("abnormal reap: last URB handled, reporting");
1860 if (tpriv->reap_action != COMPLETED_EARLY &&
1861 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1862 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
1868 itransfer->transferred += urb->actual_length;
1870 /* Many of these errors can occur on *any* urb of a multi-urb
1871 * transfer. When they do, we tear down the rest of the transfer.
1873 switch (urb->status) {
1876 case -EREMOTEIO: /* short transfer */
1878 case -ENOENT: /* cancelled */
1882 usbi_dbg("device removed");
1883 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
1884 goto cancel_remaining;
1886 usbi_dbg("detected endpoint stall");
1887 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1888 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
1889 goto cancel_remaining;
1891 /* overflow can only ever occur in the last urb */
1892 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
1893 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1894 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
1899 usbi_dbg("low level error %d", urb->status);
1900 tpriv->reap_action = ERROR;
1901 goto cancel_remaining;
1903 usbi_warn(ITRANSFER_CTX(itransfer),
1904 "unrecognised urb status %d", urb->status);
1905 tpriv->reap_action = ERROR;
1906 goto cancel_remaining;
1909 /* if we're the last urb or we got less data than requested then we're
1911 if (urb_idx == tpriv->num_urbs - 1) {
1912 usbi_dbg("last URB in transfer --> complete!");
1914 } else if (urb->actual_length < urb->buffer_length) {
1915 usbi_dbg("short transfer %d/%d --> complete!",
1916 urb->actual_length, urb->buffer_length);
1917 if (tpriv->reap_action == NORMAL)
1918 tpriv->reap_action = COMPLETED_EARLY;
1923 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
1924 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
1926 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
1929 /* cancel remaining urbs and wait for their completion before
1930 * reporting results */
1931 for (int i = tpriv->num_urbs - 1; i > urb_idx; i--) {
1932 /* remaining URBs with continuation flag are
1933 * automatically cancelled by the kernel */
1934 if (tpriv->urbs[i].flags & USBFS_URB_BULK_CONTINUATION)
1936 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1937 if (tmp && errno != EINVAL)
1938 usbi_warn(TRANSFER_CTX(transfer),
1939 "unrecognised discard errno %d", errno);
1943 usbi_mutex_unlock(&itransfer->lock);
1949 usbi_mutex_unlock(&itransfer->lock);
1950 return CANCELLED == tpriv->reap_action ?
1951 usbi_handle_transfer_cancellation(itransfer) :
1952 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
1955 static int handle_iso_completion(struct usbi_transfer *itransfer,
1956 struct usbfs_urb *urb)
1958 struct libusb_transfer *transfer =
1959 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1960 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1961 int num_urbs = tpriv->num_urbs;
1964 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
1966 usbi_mutex_lock(&itransfer->lock);
1967 for (i = 0; i < num_urbs; i++) {
1968 if (urb == tpriv->iso_urbs[i]) {
1974 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
1975 usbi_mutex_unlock(&itransfer->lock);
1976 return LIBUSB_ERROR_NOT_FOUND;
1979 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
1982 /* copy isochronous results back in */
1984 for (i = 0; i < urb->number_of_packets; i++) {
1985 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
1986 struct libusb_iso_packet_descriptor *lib_desc =
1987 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
1988 lib_desc->status = urb_desc->status;
1989 lib_desc->actual_length = urb_desc->actual_length;
1992 tpriv->num_retired++;
1994 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
1995 usbi_dbg("CANCEL: urb status %d", urb->status);
1997 if (status == LIBUSB_TRANSFER_COMPLETED)
1998 status = LIBUSB_TRANSFER_ERROR;
2000 if (tpriv->num_retired == num_urbs) {
2001 usbi_dbg("CANCEL: last URB handled, reporting");
2002 free_iso_urbs(tpriv);
2003 if (tpriv->reap_action == CANCELLED) {
2004 usbi_mutex_unlock(&itransfer->lock);
2005 return usbi_handle_transfer_cancellation(itransfer);
2007 usbi_mutex_unlock(&itransfer->lock);
2008 return usbi_handle_transfer_completion(itransfer,
2009 LIBUSB_TRANSFER_ERROR);
2015 switch (urb->status) {
2018 case -ENOENT: /* cancelled */
2021 usbi_dbg("device removed");
2022 status = LIBUSB_TRANSFER_NO_DEVICE;
2027 usbi_dbg("low-level USB error %d", urb->status);
2030 usbi_warn(TRANSFER_CTX(transfer),
2031 "unrecognised urb status %d", urb->status);
2035 /* if we're the last urb or we got less data than requested then we're
2037 if (urb_idx == num_urbs) {
2038 usbi_dbg("last URB in transfer --> complete!");
2039 free_iso_urbs(tpriv);
2040 usbi_mutex_unlock(&itransfer->lock);
2041 return usbi_handle_transfer_completion(itransfer, status);
2045 usbi_mutex_unlock(&itransfer->lock);
2049 static int handle_control_completion(struct usbi_transfer *itransfer,
2050 struct usbfs_urb *urb)
2052 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2055 usbi_mutex_lock(&itransfer->lock);
2056 usbi_dbg("handling completion status %d", urb->status);
2058 itransfer->transferred += urb->actual_length;
2060 if (tpriv->reap_action == CANCELLED) {
2061 if (urb->status != 0 && urb->status != -ENOENT)
2062 usbi_warn(ITRANSFER_CTX(itransfer),
2063 "cancel: unrecognised urb status %d", urb->status);
2066 usbi_mutex_unlock(&itransfer->lock);
2067 return usbi_handle_transfer_cancellation(itransfer);
2070 switch (urb->status) {
2072 status = LIBUSB_TRANSFER_COMPLETED;
2074 case -ENOENT: /* cancelled */
2077 usbi_dbg("device removed");
2078 status = LIBUSB_TRANSFER_NO_DEVICE;
2081 usbi_dbg("unsupported control request");
2082 status = LIBUSB_TRANSFER_STALL;
2087 usbi_dbg("low-level bus error occurred");
2088 status = LIBUSB_TRANSFER_ERROR;
2091 usbi_warn(ITRANSFER_CTX(itransfer),
2092 "unrecognised urb status %d", urb->status);
2093 status = LIBUSB_TRANSFER_ERROR;
2099 usbi_mutex_unlock(&itransfer->lock);
2100 return usbi_handle_transfer_completion(itransfer, status);
2103 static int reap_for_handle(struct libusb_device_handle *handle)
2105 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
2107 struct usbfs_urb *urb;
2108 struct usbi_transfer *itransfer;
2109 struct libusb_transfer *transfer;
2111 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2112 if (r == -1 && errno == EAGAIN)
2115 if (errno == ENODEV)
2116 return LIBUSB_ERROR_NO_DEVICE;
2118 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2120 return LIBUSB_ERROR_IO;
2123 itransfer = urb->usercontext;
2124 transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2126 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2127 urb->actual_length);
2129 switch (transfer->type) {
2130 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2131 return handle_iso_completion(itransfer, urb);
2132 case LIBUSB_TRANSFER_TYPE_BULK:
2133 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2134 return handle_bulk_completion(itransfer, urb);
2135 case LIBUSB_TRANSFER_TYPE_CONTROL:
2136 return handle_control_completion(itransfer, urb);
2138 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2140 return LIBUSB_ERROR_OTHER;
2144 static int op_handle_events(struct libusb_context *ctx,
2145 struct pollfd *fds, nfds_t nfds, int num_ready)
2150 usbi_mutex_lock(&ctx->open_devs_lock);
2151 for (i = 0; i < nfds && num_ready > 0; i++) {
2152 struct pollfd *pollfd = &fds[i];
2153 struct libusb_device_handle *handle;
2154 struct linux_device_handle_priv *hpriv = NULL;
2156 if (!pollfd->revents)
2160 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2161 hpriv = __device_handle_priv(handle);
2162 if (hpriv->fd == pollfd->fd)
2166 if (pollfd->revents & POLLERR) {
2167 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2168 usbi_handle_disconnect(handle);
2172 r = reap_for_handle(handle);
2173 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2181 usbi_mutex_unlock(&ctx->open_devs_lock);
2185 static int op_clock_gettime(int clk_id, struct timespec *tp)
2188 case USBI_CLOCK_MONOTONIC:
2189 return clock_gettime(monotonic_clkid, tp);
2190 case USBI_CLOCK_REALTIME:
2191 return clock_gettime(CLOCK_REALTIME, tp);
2193 return LIBUSB_ERROR_INVALID_PARAM;
2197 #ifdef USBI_TIMERFD_AVAILABLE
2198 static clockid_t op_get_timerfd_clockid(void)
2200 return monotonic_clkid;
2205 const struct usbi_os_backend linux_usbfs_backend = {
2206 .name = "Linux usbfs",
2209 .get_device_list = op_get_device_list,
2210 .get_device_descriptor = op_get_device_descriptor,
2211 .get_active_config_descriptor = op_get_active_config_descriptor,
2212 .get_config_descriptor = op_get_config_descriptor,
2216 .get_configuration = op_get_configuration,
2217 .set_configuration = op_set_configuration,
2218 .claim_interface = op_claim_interface,
2219 .release_interface = op_release_interface,
2221 .set_interface_altsetting = op_set_interface,
2222 .clear_halt = op_clear_halt,
2223 .reset_device = op_reset_device,
2225 .kernel_driver_active = op_kernel_driver_active,
2226 .detach_kernel_driver = op_detach_kernel_driver,
2227 .attach_kernel_driver = op_attach_kernel_driver,
2229 .destroy_device = op_destroy_device,
2231 .submit_transfer = op_submit_transfer,
2232 .cancel_transfer = op_cancel_transfer,
2233 .clear_transfer_priv = op_clear_transfer_priv,
2235 .handle_events = op_handle_events,
2237 .clock_gettime = op_clock_gettime,
2239 #ifdef USBI_TIMERFD_AVAILABLE
2240 .get_timerfd_clockid = op_get_timerfd_clockid,
2243 .device_priv_size = sizeof(struct linux_device_priv),
2244 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2245 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2246 .add_iso_packet_size = 0,