Update to new libusb
[bcusdk.git] / eibd / usb / linux_usbfs.c
blob5b1b587f3fabe6f61a21cc50e2771a93b7d9fda0
1 /*
2 * Linux usbfs backend for libusb
3 * Copyright (C) 2007-2008 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
21 #define _GNU_SOURCE
23 #include <config.h>
24 #include <ctype.h>
25 #include <dirent.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <pthread.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <unistd.h>
38 #include "libusb.h"
39 #include "libusbi.h"
40 #include "linux_usbfs.h"
42 int pthread_mutex_trylock(pthread_mutex_t *mutex)
44 return 0;
47 int clock_gettime(clockid_t clk_id, struct timespec *tp)
49 struct timeval tv;
50 gettimeofday (&tv, 0);
51 TIMEVAL_TO_TIMESPEC (&tv, tp);
52 return 0;
55 /* sysfs vs usbfs:
56 * opening a usbfs node causes the device to be resumed, so we attempt to
57 * avoid this during enumeration.
59 * sysfs allows us to read the kernel's in-memory copies of device descriptors
60 * and so forth, avoiding the need to open the device:
61 * - The binary "descriptors" file was added in 2.6.23.
62 * - The "busnum" file was added in 2.6.22
63 * - The "devnum" file has been present since pre-2.6.18
64 * - the "bConfigurationValue" file has been present since pre-2.6.18
66 * If we have bConfigurationValue, busnum, and devnum, then we can determine
67 * the active configuration without having to open the usbfs node in RDWR mode.
68 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
69 * The busnum file is important as that is the only way we can relate sysfs
70 * devices to usbfs nodes.
72 * If we also have descriptors, we can obtain the device descriptor and active
73 * configuration without touching usbfs at all.
75 * The descriptors file originally only contained the active configuration
76 * descriptor alongside the device descriptor, but all configurations are
77 * included as of Linux 2.6.26.
80 static const char *usbfs_path = NULL;
82 /* do we have a busnum to relate devices? this also implies that we can read
83 * the active configuration through bConfigurationValue */
84 static int sysfs_can_relate_devices = -1;
86 /* do we have a descriptors file? */
87 static int sysfs_has_descriptors = -1;
89 struct linux_device_priv {
90 char *sysfs_dir;
91 unsigned char *dev_descriptor;
92 unsigned char *config_descriptor;
95 struct linux_device_handle_priv {
96 int fd;
99 enum reap_action {
100 NORMAL = 0,
101 /* submission failed after the first URB, so await cancellation/completion
102 * of all the others */
103 SUBMIT_FAILED,
105 /* cancelled by user or timeout */
106 CANCELLED,
108 /* completed multi-URB transfer in non-final URB */
109 COMPLETED_EARLY,
112 struct linux_transfer_priv {
113 union {
114 struct usbfs_urb *urbs;
115 struct usbfs_urb **iso_urbs;
118 enum reap_action reap_action;
119 int num_urbs;
120 unsigned int num_retired;
122 /* next iso packet in user-supplied transfer to be populated */
123 int iso_packet_offset;
126 static void __get_usbfs_path(struct libusb_device *dev, char *path)
128 snprintf(path, PATH_MAX, "%s/%03d/%03d", usbfs_path, dev->bus_number,
129 dev->device_address);
132 static struct linux_device_priv *__device_priv(struct libusb_device *dev)
134 return (struct linux_device_priv *) dev->os_priv;
137 static struct linux_device_handle_priv *__device_handle_priv(
138 struct libusb_device_handle *handle)
140 return (struct linux_device_handle_priv *) handle->os_priv;
143 static int check_usb_vfs(const char *dirname)
145 DIR *dir;
146 struct dirent *entry;
147 int found = 0;
149 dir = opendir(dirname);
150 if (!dir)
151 return 0;
153 while ((entry = readdir(dir)) != NULL) {
154 if (entry->d_name[0] == '.')
155 continue;
157 /* We assume if we find any files that it must be the right place */
158 found = 1;
159 break;
162 closedir(dir);
163 return found;
166 static const char *find_usbfs_path(void)
168 const char *path = "/dev/bus/usb";
169 const char *ret = NULL;
171 if (check_usb_vfs(path)) {
172 ret = path;
173 } else {
174 path = "/proc/bus/usb";
175 if (check_usb_vfs(path))
176 ret = path;
179 usbi_dbg("found usbfs at %s", ret);
180 return ret;
183 static int op_init(struct libusb_context *ctx)
185 struct stat statbuf;
186 int r;
188 usbfs_path = find_usbfs_path();
189 if (!usbfs_path) {
190 usbi_err(ctx, "could not find usbfs");
191 return LIBUSB_ERROR_OTHER;
194 r = stat(SYSFS_DEVICE_PATH, &statbuf);
195 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
196 usbi_dbg("found usb devices in sysfs");
197 } else {
198 usbi_dbg("sysfs usb info not available");
199 sysfs_has_descriptors = 0;
200 sysfs_can_relate_devices = 0;
203 return 0;
206 static int usbfs_get_device_descriptor(struct libusb_device *dev,
207 unsigned char *buffer)
209 struct linux_device_priv *priv = __device_priv(dev);
211 /* return cached copy */
212 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
213 return 0;
216 static int __open_sysfs_attr(struct libusb_device *dev, const char *attr)
218 struct linux_device_priv *priv = __device_priv(dev);
219 char filename[PATH_MAX];
220 int fd;
222 snprintf(filename, PATH_MAX, "%s/%s/%s",
223 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
224 fd = open(filename, O_RDONLY);
225 if (fd < 0) {
226 usbi_err(DEVICE_CTX(dev),
227 "open %s failed ret=%d errno=%d", filename, fd, errno);
228 return LIBUSB_ERROR_IO;
231 return fd;
234 static int sysfs_get_device_descriptor(struct libusb_device *dev,
235 unsigned char *buffer)
237 int fd;
238 ssize_t r;
240 /* sysfs provides access to an in-memory copy of the device descriptor,
241 * so we use that rather than keeping our own copy */
243 fd = __open_sysfs_attr(dev, "descriptors");
244 if (fd < 0)
245 return fd;
247 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
248 close(fd);
249 if (r < 0) {
250 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
251 return LIBUSB_ERROR_IO;
252 } else if (r < DEVICE_DESC_LENGTH) {
253 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
254 return LIBUSB_ERROR_IO;
257 return 0;
260 static int op_get_device_descriptor(struct libusb_device *dev,
261 unsigned char *buffer, int *host_endian)
263 if (sysfs_has_descriptors) {
264 return sysfs_get_device_descriptor(dev, buffer);
265 } else {
266 *host_endian = 1;
267 return usbfs_get_device_descriptor(dev, buffer);
271 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
272 unsigned char *buffer, size_t len)
274 struct linux_device_priv *priv = __device_priv(dev);
275 if (!priv->config_descriptor)
276 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
278 /* retrieve cached copy */
279 memcpy(buffer, priv->config_descriptor, len);
280 return 0;
283 /* read the bConfigurationValue for a device */
284 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
286 char *endptr;
287 char tmp[4] = {0, 0, 0, 0};
288 long num;
289 int fd;
290 size_t r;
292 fd = __open_sysfs_attr(dev, "bConfigurationValue");
293 if (fd < 0)
294 return fd;
296 r = read(fd, tmp, sizeof(tmp));
297 close(fd);
298 if (r < 0) {
299 usbi_err(DEVICE_CTX(dev),
300 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
301 return LIBUSB_ERROR_IO;
302 } else if (r == 0) {
303 usbi_err(DEVICE_CTX(dev), "device unconfigured");
304 *config = -1;
305 return 0;
308 if (tmp[sizeof(tmp) - 1] != 0) {
309 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
310 return LIBUSB_ERROR_IO;
311 } else if (tmp[0] == 0) {
312 usbi_err(DEVICE_CTX(dev), "no configuration value?");
313 return LIBUSB_ERROR_IO;
316 num = strtol(tmp, &endptr, 10);
317 if (endptr == tmp) {
318 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
319 return LIBUSB_ERROR_IO;
322 *config = (int) num;
323 return 0;
326 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
327 * seeks to the next one. */
328 static int seek_to_next_config(struct libusb_context *ctx, int fd)
330 struct libusb_config_descriptor config;
331 unsigned char tmp[6];
332 off_t off;
333 int r;
335 /* read first 6 bytes of descriptor */
336 r = read(fd, tmp, sizeof(tmp));
337 if (r < 0) {
338 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
339 return LIBUSB_ERROR_IO;
340 } else if (r < sizeof(tmp)) {
341 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
342 return LIBUSB_ERROR_IO;
345 /* seek forward to end of config */
346 usbi_parse_descriptor(tmp, "bbwbb", &config, 1);
347 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
348 if (off < 0) {
349 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
350 return LIBUSB_ERROR_IO;
353 return 0;
356 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
357 unsigned char *buffer, size_t len)
359 int fd;
360 ssize_t r;
361 off_t off;
362 int to_copy;
363 int config;
364 unsigned char tmp[6];
366 r = sysfs_get_active_config(dev, &config);
367 if (r < 0)
368 return r;
369 if (config == -1)
370 return LIBUSB_ERROR_NOT_FOUND;
372 usbi_dbg("active configuration %d", config);
374 /* sysfs provides access to an in-memory copy of the device descriptor,
375 * so we use that rather than keeping our own copy */
377 fd = __open_sysfs_attr(dev, "descriptors");
378 if (fd < 0)
379 return fd;
381 /* device might have been unconfigured since we read bConfigurationValue,
382 * so first check that there is any config descriptor data at all... */
383 off = lseek(fd, 0, SEEK_END);
384 if (off < 1) {
385 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
386 off, errno);
387 close(fd);
388 return LIBUSB_ERROR_IO;
389 } else if (off == DEVICE_DESC_LENGTH) {
390 close(fd);
391 return LIBUSB_ERROR_NOT_FOUND;
394 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
395 if (off < 0) {
396 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
397 close(fd);
398 return LIBUSB_ERROR_IO;
401 /* unbounded loop: we expect the descriptor to be present under all
402 * circumstances */
403 while (1) {
404 r = read(fd, tmp, sizeof(tmp));
405 if (r < 0) {
406 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
407 fd, errno);
408 return LIBUSB_ERROR_IO;
409 } else if (r < sizeof(tmp)) {
410 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
411 return LIBUSB_ERROR_IO;
414 /* check bConfigurationValue */
415 if (tmp[5] == config)
416 break;
418 /* try the next descriptor */
419 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
420 if (off < 0)
421 return LIBUSB_ERROR_IO;
423 r = seek_to_next_config(DEVICE_CTX(dev), fd);
424 if (r < 0)
425 return r;
428 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
429 memcpy(buffer, tmp, to_copy);
430 if (len > sizeof(tmp)) {
431 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
432 if (r < 0) {
433 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
434 fd, errno);
435 r = LIBUSB_ERROR_IO;
436 } else if (r == 0) {
437 usbi_dbg("device is unconfigured");
438 r = LIBUSB_ERROR_NOT_FOUND;
439 } else if (r < len - sizeof(tmp)) {
440 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
441 r = LIBUSB_ERROR_IO;
443 } else {
444 r = 0;
447 close(fd);
448 return r;
451 static int op_get_active_config_descriptor(struct libusb_device *dev,
452 unsigned char *buffer, size_t len, int *host_endian)
454 if (sysfs_has_descriptors) {
455 return sysfs_get_active_config_descriptor(dev, buffer, len);
456 } else {
457 *host_endian = 1;
458 return usbfs_get_active_config_descriptor(dev, buffer, len);
462 /* takes a usbfs fd, attempts to find the requested config and copy a certain
463 * amount of it into an output buffer. */
464 static int get_config_descriptor(struct libusb_context *ctx, int fd,
465 uint8_t config_index, unsigned char *buffer, size_t len)
467 off_t off;
468 ssize_t r;
470 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
471 if (off < 0) {
472 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
473 return LIBUSB_ERROR_IO;
476 /* might need to skip some configuration descriptors to reach the
477 * requested configuration */
478 while (config_index > 0) {
479 r = seek_to_next_config(ctx, fd);
480 if (r < 0)
481 return r;
482 config_index--;
485 /* read the rest of the descriptor */
486 r = read(fd, buffer, len);
487 if (r < 0) {
488 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
489 return LIBUSB_ERROR_IO;
490 } else if (r < len) {
491 usbi_err(ctx, "short output read %d/%d", r, len);
492 return LIBUSB_ERROR_IO;
495 return 0;
498 static int op_get_config_descriptor(struct libusb_device *dev,
499 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
501 char filename[PATH_MAX];
502 int fd;
503 int r;
505 /* always read from usbfs: sysfs only has the active descriptor
506 * this will involve waking the device up, but oh well! */
508 /* FIXME: the above is no longer true, new kernels have all descriptors
509 * in the descriptors file. but its kinda hard to detect if the kernel
510 * is sufficiently new. */
512 __get_usbfs_path(dev, filename);
513 fd = open(filename, O_RDONLY);
514 if (fd < 0) {
515 usbi_err(DEVICE_CTX(dev),
516 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
517 return LIBUSB_ERROR_IO;
520 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
521 close(fd);
522 *host_endian = 1;
523 return r;
526 /* cache the active config descriptor in memory. a value of -1 means that
527 * we aren't sure which one is active, so just assume the first one.
528 * only for usbfs. */
529 static int cache_active_config(struct libusb_device *dev, int fd,
530 int active_config)
532 struct linux_device_priv *priv = __device_priv(dev);
533 struct libusb_config_descriptor config;
534 unsigned char tmp[8];
535 unsigned char *buf;
536 int idx;
537 int r;
539 if (active_config == -1) {
540 idx = 0;
541 } else {
542 r = usbi_get_config_index_by_value(dev, active_config, &idx);
543 if (r < 0)
544 return r;
545 if (idx == -1)
546 return LIBUSB_ERROR_NOT_FOUND;
549 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
550 if (r < 0) {
551 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
552 return r;
555 usbi_parse_descriptor(tmp, "bbw", &config, 1);
556 buf = malloc(config.wTotalLength);
557 if (!buf)
558 return LIBUSB_ERROR_NO_MEM;
560 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
561 config.wTotalLength);
562 if (r < 0) {
563 free(buf);
564 return r;
567 if (priv->config_descriptor)
568 free(priv->config_descriptor);
569 priv->config_descriptor = buf;
570 return 0;
573 /* send a control message to retrieve active configuration */
574 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
576 unsigned char active_config = 0;
577 int r;
579 struct usbfs_ctrltransfer ctrl = {
580 .bmRequestType = LIBUSB_ENDPOINT_IN,
581 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
582 .wValue = 0,
583 .wIndex = 0,
584 .wLength = 1,
585 .timeout = 1000,
586 .data = &active_config
589 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
590 if (r < 0) {
591 if (errno == ENODEV)
592 return LIBUSB_ERROR_NO_DEVICE;
594 usbi_err(DEVICE_CTX(dev),
595 "get_configuration failed ret=%d errno=%d", r, errno);
596 return LIBUSB_ERROR_IO;
599 return active_config;
602 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
603 uint8_t devaddr, const char *sysfs_dir)
605 struct linux_device_priv *priv = __device_priv(dev);
606 unsigned char *dev_buf;
607 char path[PATH_MAX];
608 int fd;
609 int active_config = 0;
610 int device_configured = 1;
611 ssize_t r;
613 dev->bus_number = busnum;
614 dev->device_address = devaddr;
616 if (sysfs_dir) {
617 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
618 if (!priv->sysfs_dir)
619 return LIBUSB_ERROR_NO_MEM;
620 strcpy(priv->sysfs_dir, sysfs_dir);
623 if (sysfs_has_descriptors)
624 return 0;
626 /* cache device descriptor in memory so that we can retrieve it later
627 * without waking the device up (op_get_device_descriptor) */
629 priv->dev_descriptor = NULL;
630 priv->config_descriptor = NULL;
632 if (sysfs_can_relate_devices) {
633 int tmp = sysfs_get_active_config(dev, &active_config);
634 if (tmp < 0)
635 return tmp;
636 if (active_config == -1)
637 device_configured = 0;
640 __get_usbfs_path(dev, path);
641 fd = open(path, O_RDWR);
642 if (fd < 0 && errno == EACCES) {
643 fd = open(path, O_RDONLY);
644 /* if we only have read-only access to the device, we cannot
645 * send a control message to determine the active config. just
646 * assume the first one is active. */
647 active_config = -1;
650 if (fd < 0) {
651 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
652 return LIBUSB_ERROR_IO;
655 if (!sysfs_can_relate_devices) {
656 if (active_config == -1) {
657 /* if we only have read-only access to the device, we cannot
658 * send a control message to determine the active config. just
659 * assume the first one is active. */
660 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
661 "determine active configuration descriptor", path);
662 } else {
663 active_config = usbfs_get_active_config(dev, fd);
664 if (active_config < 0) {
665 close(fd);
666 return active_config;
667 } else if (active_config == 0) {
668 /* some buggy devices have a configuration 0, but we're
669 * reaching into the corner of a corner case here, so let's
670 * not support buggy devices in these circumstances.
671 * stick to the specs: a configuration value of 0 means
672 * unconfigured. */
673 usbi_dbg("assuming unconfigured device");
674 device_configured = 0;
679 dev_buf = malloc(DEVICE_DESC_LENGTH);
680 if (!dev_buf) {
681 close(fd);
682 return LIBUSB_ERROR_NO_MEM;
685 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
686 if (r < 0) {
687 usbi_err(DEVICE_CTX(dev),
688 "read descriptor failed ret=%d errno=%d", fd, errno);
689 free(dev_buf);
690 close(fd);
691 return LIBUSB_ERROR_IO;
692 } else if (r < DEVICE_DESC_LENGTH) {
693 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
694 free(dev_buf);
695 close(fd);
696 return LIBUSB_ERROR_IO;
699 /* bit of a hack: set num_configurations now because cache_active_config()
700 * calls usbi_get_config_index_by_value() which uses it */
701 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
703 if (device_configured) {
704 r = cache_active_config(dev, fd, active_config);
705 if (r < 0) {
706 close(fd);
707 free(dev_buf);
708 return r;
712 close(fd);
713 priv->dev_descriptor = dev_buf;
714 return 0;
717 static int enumerate_device(struct libusb_context *ctx,
718 struct discovered_devs **_discdevs, uint8_t busnum, uint8_t devaddr,
719 const char *sysfs_dir)
721 struct discovered_devs *discdevs;
722 unsigned long session_id;
723 int need_unref = 0;
724 struct libusb_device *dev;
725 int r = 0;
727 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
728 * will be reused. instead we should add a simple sysfs attribute with
729 * a session ID. */
730 session_id = busnum << 8 | devaddr;
731 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
732 session_id);
734 dev = usbi_get_device_by_session_id(ctx, session_id);
735 if (dev) {
736 usbi_dbg("using existing device for %d/%d (session %ld)",
737 busnum, devaddr, session_id);
738 } else {
739 usbi_dbg("allocating new device for %d/%d (session %ld)",
740 busnum, devaddr, session_id);
741 dev = usbi_alloc_device(ctx, session_id);
742 if (!dev)
743 return LIBUSB_ERROR_NO_MEM;
744 need_unref = 1;
745 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
746 if (r < 0)
747 goto out;
748 r = usbi_sanitize_device(dev);
749 if (r < 0)
750 goto out;
753 discdevs = discovered_devs_append(*_discdevs, dev);
754 if (!discdevs)
755 r = LIBUSB_ERROR_NO_MEM;
756 else
757 *_discdevs = discdevs;
759 out:
760 if (need_unref)
761 libusb_unref_device(dev);
762 return r;
765 /* open a bus directory and adds all discovered devices to discdevs. on
766 * failure (non-zero return) the pre-existing discdevs should be destroyed
767 * (and devices freed). on success, the new discdevs pointer should be used
768 * as it may have been moved. */
769 static int usbfs_scan_busdir(struct libusb_context *ctx,
770 struct discovered_devs **_discdevs, uint8_t busnum)
772 DIR *dir;
773 char dirpath[PATH_MAX];
774 struct dirent *entry;
775 struct discovered_devs *discdevs = *_discdevs;
776 int r = 0;
778 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
779 usbi_dbg("%s", dirpath);
780 dir = opendir(dirpath);
781 if (!dir) {
782 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
783 /* FIXME: should handle valid race conditions like hub unplugged
784 * during directory iteration - this is not an error */
785 return LIBUSB_ERROR_IO;
788 while ((entry = readdir(dir))) {
789 int devaddr;
791 if (entry->d_name[0] == '.')
792 continue;
794 devaddr = atoi(entry->d_name);
795 if (devaddr == 0) {
796 usbi_dbg("unknown dir entry %s", entry->d_name);
797 continue;
800 r = enumerate_device(ctx, &discdevs, busnum, (uint8_t) devaddr, NULL);
801 if (r < 0)
802 goto out;
805 *_discdevs = discdevs;
806 out:
807 closedir(dir);
808 return r;
811 static int usbfs_get_device_list(struct libusb_context *ctx,
812 struct discovered_devs **_discdevs)
814 struct dirent *entry;
815 DIR *buses = opendir(usbfs_path);
816 struct discovered_devs *discdevs = *_discdevs;
817 int r = 0;
819 if (!buses) {
820 usbi_err(ctx, "opendir buses failed errno=%d", errno);
821 return LIBUSB_ERROR_IO;
824 while ((entry = readdir(buses))) {
825 struct discovered_devs *discdevs_new = discdevs;
826 int busnum;
828 if (entry->d_name[0] == '.')
829 continue;
831 busnum = atoi(entry->d_name);
832 if (busnum == 0) {
833 usbi_dbg("unknown dir entry %s", entry->d_name);
834 continue;
837 r = usbfs_scan_busdir(ctx, &discdevs_new, busnum);
838 if (r < 0)
839 goto out;
840 discdevs = discdevs_new;
843 out:
844 closedir(buses);
845 *_discdevs = discdevs;
846 return r;
850 static int sysfs_scan_device(struct libusb_context *ctx,
851 struct discovered_devs **_discdevs, const char *devname,
852 int *usbfs_fallback)
854 int r;
855 FILE *fd;
856 char filename[PATH_MAX];
857 int busnum;
858 int devaddr;
860 usbi_dbg("scan %s", devname);
862 /* determine descriptors presence ahead of time, we need to know this
863 * when we reach initialize_device */
864 if (sysfs_has_descriptors == -1) {
865 struct stat statbuf;
867 snprintf(filename, PATH_MAX, "%s/%s/descriptors", SYSFS_DEVICE_PATH,
868 devname);
869 r = stat(filename, &statbuf);
870 if (r == 0 && S_ISREG(statbuf.st_mode)) {
871 usbi_dbg("sysfs descriptors available");
872 sysfs_has_descriptors = 1;
873 } else {
874 usbi_dbg("sysfs descriptors not available");
875 sysfs_has_descriptors = 0;
879 snprintf(filename, PATH_MAX, "%s/%s/busnum", SYSFS_DEVICE_PATH, devname);
880 fd = fopen(filename, "r");
881 if (!fd) {
882 if (errno == ENOENT) {
883 usbi_dbg("busnum not found, cannot relate sysfs to usbfs, "
884 "falling back on pure usbfs");
885 sysfs_can_relate_devices = 0;
886 *usbfs_fallback = 1;
887 return LIBUSB_ERROR_OTHER;
889 usbi_err(ctx, "open busnum failed, errno=%d", errno);
890 return LIBUSB_ERROR_IO;
893 sysfs_can_relate_devices = 1;
895 r = fscanf(fd, "%d", &busnum);
896 fclose(fd);
897 if (r != 1) {
898 usbi_err(ctx, "fscanf busnum returned %d, errno=%d", r, errno);
899 return LIBUSB_ERROR_IO;
902 snprintf(filename, PATH_MAX, "%s/%s/devnum", SYSFS_DEVICE_PATH, devname);
903 fd = fopen(filename, "r");
904 if (!fd) {
905 usbi_err(ctx, "open devnum failed, errno=%d", errno);
906 return LIBUSB_ERROR_IO;
909 r = fscanf(fd, "%d", &devaddr);
910 fclose(fd);
911 if (r != 1) {
912 usbi_err(ctx, "fscanf devnum returned %d, errno=%d", r, errno);
913 return LIBUSB_ERROR_IO;
916 usbi_dbg("bus=%d dev=%d", busnum, devaddr);
917 if (busnum > 255 || devaddr > 255)
918 return LIBUSB_ERROR_INVALID_PARAM;
920 return enumerate_device(ctx, _discdevs, busnum & 0xff, devaddr & 0xff,
921 devname);
924 static int sysfs_get_device_list(struct libusb_context *ctx,
925 struct discovered_devs **_discdevs, int *usbfs_fallback)
927 struct discovered_devs *discdevs = *_discdevs;
928 DIR *devices = opendir(SYSFS_DEVICE_PATH);
929 struct dirent *entry;
930 int r = 0;
932 if (!devices) {
933 usbi_err(ctx, "opendir devices failed errno=%d", errno);
934 return LIBUSB_ERROR_IO;
937 while ((entry = readdir(devices))) {
938 struct discovered_devs *discdevs_new = discdevs;
940 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
941 || strchr(entry->d_name, ':'))
942 continue;
944 r = sysfs_scan_device(ctx, &discdevs_new, entry->d_name,
945 usbfs_fallback);
946 if (r < 0)
947 goto out;
948 discdevs = discdevs_new;
951 out:
952 closedir(devices);
953 *_discdevs = discdevs;
954 return r;
957 static int op_get_device_list(struct libusb_context *ctx,
958 struct discovered_devs **_discdevs)
960 /* we can retrieve device list and descriptors from sysfs or usbfs.
961 * sysfs is preferable, because if we use usbfs we end up resuming
962 * any autosuspended USB devices. however, sysfs is not available
963 * everywhere, so we need a usbfs fallback too.
965 * as described in the "sysfs vs usbfs" comment, sometimes we have
966 * sysfs but not enough information to relate sysfs devices to usbfs
967 * nodes. the usbfs_fallback variable is used to indicate that we should
968 * fall back on usbfs.
970 if (sysfs_can_relate_devices != 0) {
971 int usbfs_fallback = 0;
972 int r = sysfs_get_device_list(ctx, _discdevs, &usbfs_fallback);
973 if (!usbfs_fallback)
974 return r;
977 return usbfs_get_device_list(ctx, _discdevs);
980 static int op_open(struct libusb_device_handle *handle)
982 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
983 char filename[PATH_MAX];
985 __get_usbfs_path(handle->dev, filename);
986 hpriv->fd = open(filename, O_RDWR);
987 if (hpriv->fd < 0) {
988 if (errno == EACCES) {
989 fprintf(stderr, "libusb couldn't open USB device %s: "
990 "Permission denied.\n"
991 "libusb requires write access to USB device nodes.\n",
992 filename);
993 return LIBUSB_ERROR_ACCESS;
994 } else if (errno == ENOENT) {
995 return LIBUSB_ERROR_NO_DEVICE;
996 } else {
997 usbi_err(HANDLE_CTX(handle),
998 "open failed, code %d errno %d", hpriv->fd, errno);
999 return LIBUSB_ERROR_IO;
1003 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1006 static void op_close(struct libusb_device_handle *dev_handle)
1008 int fd = __device_handle_priv(dev_handle)->fd;
1009 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1010 close(fd);
1013 static int op_get_configuration(struct libusb_device_handle *handle,
1014 int *config)
1016 int r;
1017 if (sysfs_can_relate_devices != 1)
1018 return LIBUSB_ERROR_NOT_SUPPORTED;
1020 r = sysfs_get_active_config(handle->dev, config);
1021 if (*config == -1)
1022 *config = 0;
1024 return 0;
1027 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1029 struct linux_device_priv *priv = __device_priv(handle->dev);
1030 int fd = __device_handle_priv(handle)->fd;
1031 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1032 if (r) {
1033 if (errno == EINVAL)
1034 return LIBUSB_ERROR_NOT_FOUND;
1035 else if (errno == EBUSY)
1036 return LIBUSB_ERROR_BUSY;
1037 else if (errno == ENODEV)
1038 return LIBUSB_ERROR_NO_DEVICE;
1040 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1041 return LIBUSB_ERROR_OTHER;
1044 if (!sysfs_has_descriptors) {
1045 /* update our cached active config descriptor */
1046 if (config == -1) {
1047 if (priv->config_descriptor) {
1048 free(priv->config_descriptor);
1049 priv->config_descriptor = NULL;
1051 } else {
1052 r = cache_active_config(handle->dev, fd, config);
1053 if (r < 0)
1054 usbi_warn(HANDLE_CTX(handle),
1055 "failed to update cached config descriptor, error %d", r);
1059 return 0;
1062 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1064 int fd = __device_handle_priv(handle)->fd;
1065 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1066 if (r) {
1067 if (errno == ENOENT)
1068 return LIBUSB_ERROR_NOT_FOUND;
1069 else if (errno == EBUSY)
1070 return LIBUSB_ERROR_BUSY;
1071 else if (errno == ENODEV)
1072 return LIBUSB_ERROR_NO_DEVICE;
1074 usbi_err(HANDLE_CTX(handle),
1075 "claim interface failed, error %d errno %d", r, errno);
1076 return LIBUSB_ERROR_OTHER;
1078 return 0;
1081 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1083 int fd = __device_handle_priv(handle)->fd;
1084 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1085 if (r) {
1086 if (errno == ENODEV)
1087 return LIBUSB_ERROR_NO_DEVICE;
1089 usbi_err(HANDLE_CTX(handle),
1090 "release interface failed, error %d errno %d", r, errno);
1091 return LIBUSB_ERROR_OTHER;
1093 return 0;
1096 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1097 int altsetting)
1099 int fd = __device_handle_priv(handle)->fd;
1100 struct usbfs_setinterface setintf;
1101 int r;
1103 setintf.interface = iface;
1104 setintf.altsetting = altsetting;
1105 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1106 if (r) {
1107 if (errno == EINVAL)
1108 return LIBUSB_ERROR_NOT_FOUND;
1109 else if (errno == ENODEV)
1110 return LIBUSB_ERROR_NO_DEVICE;
1112 usbi_err(HANDLE_CTX(handle),
1113 "setintf failed error %d errno %d", r, errno);
1114 return LIBUSB_ERROR_OTHER;
1117 return 0;
1120 static int op_clear_halt(struct libusb_device_handle *handle,
1121 unsigned char endpoint)
1123 int fd = __device_handle_priv(handle)->fd;
1124 unsigned int _endpoint = endpoint;
1125 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1126 if (r) {
1127 if (errno == ENOENT)
1128 return LIBUSB_ERROR_NOT_FOUND;
1129 else if (errno == ENODEV)
1130 return LIBUSB_ERROR_NO_DEVICE;
1132 usbi_err(HANDLE_CTX(handle),
1133 "clear_halt failed error %d errno %d", r, errno);
1134 return LIBUSB_ERROR_OTHER;
1137 return 0;
1140 static int op_reset_device(struct libusb_device_handle *handle)
1142 int fd = __device_handle_priv(handle)->fd;
1143 int r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1144 if (r) {
1145 if (errno == ENODEV)
1146 return LIBUSB_ERROR_NOT_FOUND;
1148 usbi_err(HANDLE_CTX(handle),
1149 "reset failed error %d errno %d", r, errno);
1150 return LIBUSB_ERROR_OTHER;
1153 return 0;
1156 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1157 int interface)
1159 int fd = __device_handle_priv(handle)->fd;
1160 struct usbfs_getdriver getdrv;
1161 int r;
1163 getdrv.interface = interface;
1164 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1165 if (r) {
1166 if (errno == ENODATA)
1167 return 0;
1168 else if (errno == ENODEV)
1169 return LIBUSB_ERROR_NO_DEVICE;
1171 usbi_err(HANDLE_CTX(handle),
1172 "get driver failed error %d errno %d", r, errno);
1173 return LIBUSB_ERROR_OTHER;
1176 return 1;
1179 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1180 int interface)
1182 int fd = __device_handle_priv(handle)->fd;
1183 struct usbfs_ioctl command;
1184 int r;
1186 command.ifno = interface;
1187 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1188 command.data = NULL;
1190 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1191 if (r) {
1192 if (errno == ENODATA)
1193 return LIBUSB_ERROR_NOT_FOUND;
1194 else if (errno == EINVAL)
1195 return LIBUSB_ERROR_INVALID_PARAM;
1196 else if (errno == ENODEV)
1197 return LIBUSB_ERROR_NO_DEVICE;
1199 usbi_err(HANDLE_CTX(handle),
1200 "detach failed error %d errno %d", r, errno);
1201 return LIBUSB_ERROR_OTHER;
1204 return 0;
1207 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1208 int interface)
1210 int fd = __device_handle_priv(handle)->fd;
1211 struct usbfs_ioctl command;
1212 int r;
1214 command.ifno = interface;
1215 command.ioctl_code = IOCTL_USBFS_CONNECT;
1216 command.data = NULL;
1218 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1219 if (r < 0) {
1220 if (errno == ENODATA)
1221 return LIBUSB_ERROR_NOT_FOUND;
1222 else if (errno == EINVAL)
1223 return LIBUSB_ERROR_INVALID_PARAM;
1224 else if (errno == ENODEV)
1225 return LIBUSB_ERROR_NO_DEVICE;
1226 else if (errno == EBUSY)
1227 return LIBUSB_ERROR_BUSY;
1229 usbi_err(HANDLE_CTX(handle),
1230 "attach failed error %d errno %d", r, errno);
1231 return LIBUSB_ERROR_OTHER;
1232 } else if (r == 0) {
1233 return LIBUSB_ERROR_NOT_FOUND;
1236 return 0;
1239 static void op_destroy_device(struct libusb_device *dev)
1241 struct linux_device_priv *priv = __device_priv(dev);
1242 if (!sysfs_has_descriptors) {
1243 if (priv->dev_descriptor)
1244 free(priv->dev_descriptor);
1245 if (priv->config_descriptor)
1246 free(priv->config_descriptor);
1248 if (priv->sysfs_dir)
1249 free(priv->sysfs_dir);
1252 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1254 int i;
1255 for (i = 0; i < tpriv->num_urbs; i++) {
1256 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1257 if (!urb)
1258 break;
1259 free(urb);
1262 free(tpriv->iso_urbs);
1263 tpriv->iso_urbs = NULL;
1266 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1267 unsigned char urb_type)
1269 struct libusb_transfer *transfer =
1270 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1271 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1272 struct linux_device_handle_priv *dpriv =
1273 __device_handle_priv(transfer->dev_handle);
1274 struct usbfs_urb *urbs;
1275 int r;
1276 int i;
1277 size_t alloc_size;
1279 if (tpriv->urbs)
1280 return LIBUSB_ERROR_BUSY;
1282 /* usbfs places a 16kb limit on bulk URBs. we divide up larger requests
1283 * into smaller units to meet such restriction, then fire off all the
1284 * units at once. it would be simpler if we just fired one unit at a time,
1285 * but there is a big performance gain through doing it this way. */
1286 int num_urbs = transfer->length / MAX_BULK_BUFFER_LENGTH;
1287 int last_urb_partial = 0;
1289 if ((transfer->length % MAX_BULK_BUFFER_LENGTH) > 0) {
1290 last_urb_partial = 1;
1291 num_urbs++;
1293 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1294 transfer->length);
1295 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1296 urbs = malloc(alloc_size);
1297 if (!urbs)
1298 return LIBUSB_ERROR_NO_MEM;
1299 memset(urbs, 0, alloc_size);
1300 tpriv->urbs = urbs;
1301 tpriv->num_urbs = num_urbs;
1302 tpriv->num_retired = 0;
1303 tpriv->reap_action = NORMAL;
1305 for (i = 0; i < num_urbs; i++) {
1306 struct usbfs_urb *urb = &urbs[i];
1307 urb->usercontext = itransfer;
1308 urb->type = urb_type;
1309 urb->endpoint = transfer->endpoint;
1310 urb->buffer = transfer->buffer + (i * MAX_BULK_BUFFER_LENGTH);
1311 if (i == num_urbs - 1 && last_urb_partial)
1312 urb->buffer_length = transfer->length % MAX_BULK_BUFFER_LENGTH;
1313 else
1314 urb->buffer_length = MAX_BULK_BUFFER_LENGTH;
1316 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1317 if (r < 0) {
1318 int j;
1320 if (errno == ENODEV) {
1321 r = LIBUSB_ERROR_NO_DEVICE;
1322 } else {
1323 usbi_err(TRANSFER_CTX(transfer),
1324 "submiturb failed error %d errno=%d", r, errno);
1325 r = LIBUSB_ERROR_IO;
1328 /* if the first URB submission fails, we can simply free up and
1329 * return failure immediately. */
1330 if (i == 0) {
1331 usbi_dbg("first URB failed, easy peasy");
1332 free(urbs);
1333 tpriv->urbs = NULL;
1334 return r;
1337 /* if it's not the first URB that failed, the situation is a bit
1338 * tricky. we must discard all previous URBs. there are
1339 * complications:
1340 * - discarding is asynchronous - discarded urbs will be reaped
1341 * later. the user must not have freed the transfer when the
1342 * discarded URBs are reaped, otherwise libusb will be using
1343 * freed memory.
1344 * - the earlier URBs may have completed successfully and we do
1345 * not want to throw away any data.
1346 * so, in this case we discard all the previous URBs BUT we report
1347 * that the transfer was submitted successfully. then later when
1348 * the final discard completes we can report error to the user.
1350 tpriv->reap_action = SUBMIT_FAILED;
1352 /* The URBs we haven't submitted yet we count as already
1353 * retired. */
1354 tpriv->num_retired += num_urbs - i;
1355 for (j = 0; j < i; j++) {
1356 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &urbs[j]);
1357 if (tmp && errno != EINVAL)
1358 usbi_warn(TRANSFER_CTX(transfer),
1359 "unrecognised discard errno %d", errno);
1362 usbi_dbg("reporting successful submission but waiting for %d "
1363 "discards before reporting error", i);
1364 return 0;
1368 return 0;
1371 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1373 struct libusb_transfer *transfer =
1374 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1375 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1376 struct linux_device_handle_priv *dpriv =
1377 __device_handle_priv(transfer->dev_handle);
1378 struct usbfs_urb **urbs;
1379 size_t alloc_size;
1380 int num_packets = transfer->num_iso_packets;
1381 int i;
1382 int this_urb_len = 0;
1383 int num_urbs = 1;
1384 int packet_offset = 0;
1385 unsigned int packet_len;
1386 unsigned char *urb_buffer = transfer->buffer;
1388 if (tpriv->iso_urbs)
1389 return LIBUSB_ERROR_BUSY;
1391 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1392 * into smaller units to meet such restriction, then fire off all the
1393 * units at once. it would be simpler if we just fired one unit at a time,
1394 * but there is a big performance gain through doing it this way. */
1396 /* calculate how many URBs we need */
1397 for (i = 0; i < num_packets; i++) {
1398 int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1399 packet_len = transfer->iso_packet_desc[i].length;
1401 if (packet_len > space_remaining) {
1402 num_urbs++;
1403 this_urb_len = packet_len;
1404 } else {
1405 this_urb_len += packet_len;
1408 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1410 alloc_size = num_urbs * sizeof(*urbs);
1411 urbs = malloc(alloc_size);
1412 if (!urbs)
1413 return LIBUSB_ERROR_NO_MEM;
1414 memset(urbs, 0, alloc_size);
1416 tpriv->iso_urbs = urbs;
1417 tpriv->num_urbs = num_urbs;
1418 tpriv->num_retired = 0;
1419 tpriv->reap_action = NORMAL;
1420 tpriv->iso_packet_offset = 0;
1422 /* allocate + initialize each URB with the correct number of packets */
1423 for (i = 0; i < num_urbs; i++) {
1424 struct usbfs_urb *urb;
1425 int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1426 int urb_packet_offset = 0;
1427 unsigned char *urb_buffer_orig = urb_buffer;
1428 int j;
1429 int k;
1431 /* swallow up all the packets we can fit into this URB */
1432 while (packet_offset < transfer->num_iso_packets) {
1433 packet_len = transfer->iso_packet_desc[packet_offset].length;
1434 if (packet_len <= space_remaining_in_urb) {
1435 /* throw it in */
1436 urb_packet_offset++;
1437 packet_offset++;
1438 space_remaining_in_urb -= packet_len;
1439 urb_buffer += packet_len;
1440 } else {
1441 /* it can't fit, save it for the next URB */
1442 break;
1446 alloc_size = sizeof(*urb)
1447 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1448 urb = malloc(alloc_size);
1449 if (!urb) {
1450 free_iso_urbs(tpriv);
1451 return LIBUSB_ERROR_NO_MEM;
1453 memset(urb, 0, alloc_size);
1454 urbs[i] = urb;
1456 /* populate packet lengths */
1457 for (j = 0, k = packet_offset - urb_packet_offset;
1458 k < packet_offset; k++, j++) {
1459 packet_len = transfer->iso_packet_desc[k].length;
1460 urb->iso_frame_desc[j].length = packet_len;
1463 urb->usercontext = itransfer;
1464 urb->type = USBFS_URB_TYPE_ISO;
1465 /* FIXME: interface for non-ASAP data? */
1466 urb->flags = USBFS_URB_ISO_ASAP;
1467 urb->endpoint = transfer->endpoint;
1468 urb->number_of_packets = urb_packet_offset;
1469 urb->buffer = urb_buffer_orig;
1472 /* submit URBs */
1473 for (i = 0; i < num_urbs; i++) {
1474 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1475 if (r < 0) {
1476 int j;
1478 if (errno == ENODEV) {
1479 r = LIBUSB_ERROR_NO_DEVICE;
1480 } else {
1481 usbi_err(TRANSFER_CTX(transfer),
1482 "submiturb failed error %d errno=%d", r, errno);
1483 r = LIBUSB_ERROR_IO;
1486 /* if the first URB submission fails, we can simply free up and
1487 * return failure immediately. */
1488 if (i == 0) {
1489 usbi_dbg("first URB failed, easy peasy");
1490 free_iso_urbs(tpriv);
1491 return r;
1494 /* if it's not the first URB that failed, the situation is a bit
1495 * tricky. we must discard all previous URBs. there are
1496 * complications:
1497 * - discarding is asynchronous - discarded urbs will be reaped
1498 * later. the user must not have freed the transfer when the
1499 * discarded URBs are reaped, otherwise libusb will be using
1500 * freed memory.
1501 * - the earlier URBs may have completed successfully and we do
1502 * not want to throw away any data.
1503 * so, in this case we discard all the previous URBs BUT we report
1504 * that the transfer was submitted successfully. then later when
1505 * the final discard completes we can report error to the user.
1507 tpriv->reap_action = SUBMIT_FAILED;
1509 /* The URBs we haven't submitted yet we count as already
1510 * retired. */
1511 tpriv->num_retired = num_urbs - i;
1512 for (j = 0; j < i; j++) {
1513 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urbs[j]);
1514 if (tmp && errno != EINVAL)
1515 usbi_warn(TRANSFER_CTX(transfer),
1516 "unrecognised discard errno %d", errno);
1519 usbi_dbg("reporting successful submission but waiting for %d "
1520 "discards before reporting error", i);
1521 return 0;
1525 return 0;
1528 static int submit_control_transfer(struct usbi_transfer *itransfer)
1530 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1531 struct libusb_transfer *transfer =
1532 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1533 struct linux_device_handle_priv *dpriv =
1534 __device_handle_priv(transfer->dev_handle);
1535 struct usbfs_urb *urb;
1536 int r;
1538 if (tpriv->urbs)
1539 return LIBUSB_ERROR_BUSY;
1541 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1542 return LIBUSB_ERROR_INVALID_PARAM;
1544 urb = malloc(sizeof(struct usbfs_urb));
1545 if (!urb)
1546 return LIBUSB_ERROR_NO_MEM;
1547 memset(urb, 0, sizeof(struct usbfs_urb));
1548 tpriv->urbs = urb;
1549 tpriv->reap_action = NORMAL;
1551 urb->usercontext = itransfer;
1552 urb->type = USBFS_URB_TYPE_CONTROL;
1553 urb->endpoint = transfer->endpoint;
1554 urb->buffer = transfer->buffer;
1555 urb->buffer_length = transfer->length;
1557 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1558 if (r < 0) {
1559 free(urb);
1560 tpriv->urbs = NULL;
1561 if (errno == ENODEV)
1562 return LIBUSB_ERROR_NO_DEVICE;
1564 usbi_err(TRANSFER_CTX(transfer),
1565 "submiturb failed error %d errno=%d", r, errno);
1566 return LIBUSB_ERROR_IO;
1568 return 0;
1571 static int op_submit_transfer(struct usbi_transfer *itransfer)
1573 struct libusb_transfer *transfer =
1574 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1576 switch (transfer->type) {
1577 case LIBUSB_TRANSFER_TYPE_CONTROL:
1578 return submit_control_transfer(itransfer);
1579 case LIBUSB_TRANSFER_TYPE_BULK:
1580 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1581 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1582 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1583 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1584 return submit_iso_transfer(itransfer);
1585 default:
1586 usbi_err(TRANSFER_CTX(transfer),
1587 "unknown endpoint type %d", transfer->type);
1588 return LIBUSB_ERROR_INVALID_PARAM;
1592 static int cancel_control_transfer(struct usbi_transfer *itransfer)
1594 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1595 struct libusb_transfer *transfer =
1596 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1597 struct linux_device_handle_priv *dpriv =
1598 __device_handle_priv(transfer->dev_handle);
1599 int r;
1601 if (!tpriv->urbs)
1602 return LIBUSB_ERROR_NOT_FOUND;
1604 tpriv->reap_action = CANCELLED;
1605 r = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->urbs);
1606 if(r) {
1607 if (errno == EINVAL) {
1608 usbi_dbg("URB not found --> assuming ready to be reaped");
1609 return 0;
1610 } else {
1611 usbi_err(TRANSFER_CTX(transfer),
1612 "unrecognised DISCARD code %d", errno);
1613 return LIBUSB_ERROR_OTHER;
1617 return 0;
1620 static int cancel_bulk_transfer(struct usbi_transfer *itransfer)
1622 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1623 struct libusb_transfer *transfer =
1624 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1625 struct linux_device_handle_priv *dpriv =
1626 __device_handle_priv(transfer->dev_handle);
1627 int i;
1629 if (!tpriv->urbs)
1630 return LIBUSB_ERROR_NOT_FOUND;
1632 tpriv->reap_action = CANCELLED;
1633 for (i = 0; i < tpriv->num_urbs; i++) {
1634 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1635 if (tmp && errno != EINVAL)
1636 usbi_warn(TRANSFER_CTX(transfer),
1637 "unrecognised discard errno %d", errno);
1639 return 0;
1642 static int cancel_iso_transfer(struct usbi_transfer *itransfer)
1644 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1645 struct libusb_transfer *transfer =
1646 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1647 struct linux_device_handle_priv *dpriv =
1648 __device_handle_priv(transfer->dev_handle);
1649 int i;
1651 if (!tpriv->iso_urbs)
1652 return LIBUSB_ERROR_NOT_FOUND;
1654 tpriv->reap_action = CANCELLED;
1655 for (i = 0; i < tpriv->num_urbs; i++) {
1656 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->iso_urbs[i]);
1657 if (tmp && errno != EINVAL)
1658 usbi_warn(TRANSFER_CTX(transfer),
1659 "unrecognised discard errno %d", errno);
1661 return 0;
1664 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1666 struct libusb_transfer *transfer =
1667 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1669 switch (transfer->type) {
1670 case LIBUSB_TRANSFER_TYPE_CONTROL:
1671 return cancel_control_transfer(itransfer);
1672 case LIBUSB_TRANSFER_TYPE_BULK:
1673 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1674 return cancel_bulk_transfer(itransfer);
1675 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1676 return cancel_iso_transfer(itransfer);
1677 default:
1678 usbi_err(TRANSFER_CTX(transfer),
1679 "unknown endpoint type %d", transfer->type);
1680 return LIBUSB_ERROR_INVALID_PARAM;
1684 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1686 struct libusb_transfer *transfer =
1687 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1688 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1690 switch (transfer->type) {
1691 case LIBUSB_TRANSFER_TYPE_CONTROL:
1692 case LIBUSB_TRANSFER_TYPE_BULK:
1693 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1694 free(tpriv->urbs);
1695 tpriv->urbs = NULL;
1696 break;
1697 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1698 free_iso_urbs(tpriv);
1699 break;
1700 default:
1701 usbi_err(TRANSFER_CTX(transfer),
1702 "unknown endpoint type %d", transfer->type);
1706 static int handle_bulk_completion(struct usbi_transfer *itransfer,
1707 struct usbfs_urb *urb)
1709 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1710 int num_urbs = tpriv->num_urbs;
1711 int urb_idx = urb - tpriv->urbs;
1712 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
1714 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1715 urb_idx + 1, num_urbs);
1717 tpriv->num_retired++;
1719 if (urb->status == 0 ||
1720 (urb->status == -EOVERFLOW && urb->actual_length > 0))
1721 itransfer->transferred += urb->actual_length;
1723 if (tpriv->reap_action != NORMAL) {
1724 /* cancelled, submit_fail, or completed early */
1725 if (urb->status == 0 && tpriv->reap_action == COMPLETED_EARLY) {
1726 /* FIXME we could solve this extreme corner case with a memmove
1727 * or something */
1728 usbi_warn(ITRANSFER_CTX(itransfer), "SOME DATA LOST! "
1729 "(completed early but remaining urb completed)");
1731 usbi_dbg("CANCEL: urb status %d", urb->status);
1733 if (tpriv->num_retired == num_urbs) {
1734 usbi_dbg("CANCEL: last URB handled, reporting");
1735 if (tpriv->reap_action == CANCELLED) {
1736 free(tpriv->urbs);
1737 tpriv->urbs = NULL;
1738 usbi_handle_transfer_cancellation(itransfer);
1739 return 0;
1741 if (tpriv->reap_action != COMPLETED_EARLY)
1742 status = LIBUSB_TRANSFER_ERROR;
1743 goto out;
1745 return 0;
1748 switch (urb->status) {
1749 case 0:
1750 break;
1751 case -EPIPE:
1752 usbi_dbg("detected endpoint stall");
1753 status = LIBUSB_TRANSFER_STALL;
1754 goto out;
1755 case -EOVERFLOW:
1756 /* overflow can only ever occur in the last urb */
1757 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
1758 status = LIBUSB_TRANSFER_OVERFLOW;
1759 goto out;
1760 case -ETIME:
1761 case -EPROTO:
1762 case -EILSEQ:
1763 usbi_dbg("low level error %d", urb->status);
1764 status = LIBUSB_TRANSFER_ERROR;
1765 goto out;
1766 default:
1767 usbi_warn(ITRANSFER_CTX(itransfer),
1768 "unrecognised urb status %d", urb->status);
1769 status = LIBUSB_TRANSFER_ERROR;
1770 goto out;
1773 /* if we're the last urb or we got less data than requested then we're
1774 * done */
1775 if (urb_idx == num_urbs - 1) {
1776 usbi_dbg("last URB in transfer --> complete!");
1777 } else if (urb->actual_length < urb->buffer_length) {
1778 struct libusb_transfer *transfer =
1779 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1780 struct linux_device_handle_priv *dpriv =
1781 __device_handle_priv(transfer->dev_handle);
1782 int i;
1784 usbi_dbg("short transfer %d/%d --> complete!", urb->actual_length,
1785 urb->buffer_length);
1787 /* we have to cancel the remaining urbs and wait for their completion
1788 * before reporting results */
1789 tpriv->reap_action = COMPLETED_EARLY;
1790 for (i = urb_idx + 1; i < tpriv->num_urbs; i++) {
1791 int r = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1792 if (r && errno != EINVAL)
1793 usbi_warn(TRANSFER_CTX(transfer),
1794 "unrecognised discard errno %d", errno);
1796 return 0;
1797 } else {
1798 return 0;
1801 out:
1802 free(tpriv->urbs);
1803 tpriv->urbs = NULL;
1804 usbi_handle_transfer_completion(itransfer, status);
1805 return 0;
1808 static int handle_iso_completion(struct usbi_transfer *itransfer,
1809 struct usbfs_urb *urb)
1811 struct libusb_transfer *transfer =
1812 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1813 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1814 int num_urbs = tpriv->num_urbs;
1815 int urb_idx = 0;
1816 int i;
1818 for (i = 0; i < num_urbs; i++) {
1819 if (urb == tpriv->iso_urbs[i]) {
1820 urb_idx = i + 1;
1821 break;
1824 if (urb_idx == 0) {
1825 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
1826 return LIBUSB_ERROR_NOT_FOUND;
1829 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
1830 urb_idx, num_urbs);
1832 if (urb->status == 0) {
1833 /* copy isochronous results back in */
1835 for (i = 0; i < urb->number_of_packets; i++) {
1836 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
1837 struct libusb_iso_packet_descriptor *lib_desc =
1838 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
1839 lib_desc->status = urb_desc->status;
1840 lib_desc->actual_length = urb_desc->actual_length;
1844 tpriv->num_retired++;
1846 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
1847 usbi_dbg("CANCEL: urb status %d", urb->status);
1849 if (tpriv->num_retired == num_urbs) {
1850 usbi_dbg("CANCEL: last URB handled, reporting");
1851 free_iso_urbs(tpriv);
1852 if (tpriv->reap_action == CANCELLED)
1853 usbi_handle_transfer_cancellation(itransfer);
1854 else
1855 usbi_handle_transfer_completion(itransfer,
1856 LIBUSB_TRANSFER_ERROR);
1858 return 0;
1861 switch (urb->status) {
1862 case 0:
1863 break;
1864 case -ETIME:
1865 case -EPROTO:
1866 case -EILSEQ:
1867 usbi_dbg("low-level USB error %d", urb->status);
1868 break;
1869 default:
1870 usbi_warn(TRANSFER_CTX(transfer),
1871 "unrecognised urb status %d", urb->status);
1872 break;
1875 /* if we're the last urb or we got less data than requested then we're
1876 * done */
1877 if (urb_idx == num_urbs) {
1878 usbi_dbg("last URB in transfer --> complete!");
1879 free_iso_urbs(tpriv);
1880 usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED);
1883 return 0;
1886 static int handle_control_completion(struct usbi_transfer *itransfer,
1887 struct usbfs_urb *urb)
1889 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1890 int status;
1892 usbi_dbg("handling completion status %d", urb->status);
1894 if (urb->status == 0)
1895 itransfer->transferred += urb->actual_length;
1897 if (tpriv->reap_action == CANCELLED) {
1898 if (urb->status != 0 && urb->status != -ENOENT)
1899 usbi_warn(ITRANSFER_CTX(itransfer),
1900 "cancel: unrecognised urb status %d", urb->status);
1901 free(tpriv->urbs);
1902 tpriv->urbs = NULL;
1903 usbi_handle_transfer_cancellation(itransfer);
1904 return 0;
1907 switch (urb->status) {
1908 case 0:
1909 itransfer->transferred = urb->actual_length;
1910 status = LIBUSB_TRANSFER_COMPLETED;
1911 break;
1912 case -EPIPE:
1913 usbi_dbg("unsupported control request");
1914 status = LIBUSB_TRANSFER_STALL;
1915 break;
1916 case -ETIME:
1917 case -EPROTO:
1918 case -EILSEQ:
1919 usbi_dbg("low-level bus error occurred");
1920 status = LIBUSB_TRANSFER_ERROR;
1921 break;
1922 default:
1923 usbi_warn(ITRANSFER_CTX(itransfer),
1924 "unrecognised urb status %d", urb->status);
1925 status = LIBUSB_TRANSFER_ERROR;
1926 break;
1929 free(tpriv->urbs);
1930 tpriv->urbs = NULL;
1931 usbi_handle_transfer_completion(itransfer, status);
1932 return 0;
1935 static int reap_for_handle(struct libusb_device_handle *handle)
1937 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
1938 int r;
1939 struct usbfs_urb *urb;
1940 struct usbi_transfer *itransfer;
1941 struct libusb_transfer *transfer;
1943 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
1944 if (r == -1 && errno == EAGAIN)
1945 return 1;
1946 if (r < 0) {
1947 if (errno == ENODEV)
1948 return LIBUSB_ERROR_NO_DEVICE;
1950 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
1951 r, errno);
1952 return LIBUSB_ERROR_IO;
1955 itransfer = urb->usercontext;
1956 transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1958 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
1959 urb->actual_length);
1961 switch (transfer->type) {
1962 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1963 return handle_iso_completion(itransfer, urb);
1964 case LIBUSB_TRANSFER_TYPE_BULK:
1965 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1966 return handle_bulk_completion(itransfer, urb);
1967 case LIBUSB_TRANSFER_TYPE_CONTROL:
1968 return handle_control_completion(itransfer, urb);
1969 default:
1970 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
1971 transfer->type);
1972 return LIBUSB_ERROR_OTHER;
1976 static int op_handle_events(struct libusb_context *ctx,
1977 struct pollfd *fds, nfds_t nfds, int num_ready)
1979 int r;
1980 int i = 0;
1982 pthread_mutex_lock(&ctx->open_devs_lock);
1983 for (i = 0; i < nfds && num_ready > 0; i++) {
1984 struct pollfd *pollfd = &fds[i];
1985 struct libusb_device_handle *handle;
1986 struct linux_device_handle_priv *hpriv = NULL;
1988 if (!pollfd->revents)
1989 continue;
1991 num_ready--;
1992 list_for_each_entry(handle, &ctx->open_devs, list) {
1993 hpriv = __device_handle_priv(handle);
1994 if (hpriv->fd == pollfd->fd)
1995 break;
1998 if (pollfd->revents & POLLERR) {
1999 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2000 usbi_handle_disconnect(handle);
2001 continue;
2004 r = reap_for_handle(handle);
2005 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2006 continue;
2007 else if (r < 0)
2008 goto out;
2011 r = 0;
2012 out:
2013 pthread_mutex_unlock(&ctx->open_devs_lock);
2014 return r;
2017 static int op_clock_gettime(int clk_id, struct timespec *tp)
2019 switch (clk_id) {
2020 case USBI_CLOCK_MONOTONIC:
2021 return clock_gettime(CLOCK_MONOTONIC, tp);
2022 case USBI_CLOCK_REALTIME:
2023 return clock_gettime(CLOCK_REALTIME, tp);
2024 default:
2025 return LIBUSB_ERROR_INVALID_PARAM;
2029 const struct usbi_os_backend linux_usbfs_backend = {
2030 .name = "Linux usbfs",
2031 .init = op_init,
2032 .exit = NULL,
2033 .get_device_list = op_get_device_list,
2034 .get_device_descriptor = op_get_device_descriptor,
2035 .get_active_config_descriptor = op_get_active_config_descriptor,
2036 .get_config_descriptor = op_get_config_descriptor,
2038 .open = op_open,
2039 .close = op_close,
2040 .get_configuration = op_get_configuration,
2041 .set_configuration = op_set_configuration,
2042 .claim_interface = op_claim_interface,
2043 .release_interface = op_release_interface,
2045 .set_interface_altsetting = op_set_interface,
2046 .clear_halt = op_clear_halt,
2047 .reset_device = op_reset_device,
2049 .kernel_driver_active = op_kernel_driver_active,
2050 .detach_kernel_driver = op_detach_kernel_driver,
2051 .attach_kernel_driver = op_attach_kernel_driver,
2053 .destroy_device = op_destroy_device,
2055 .submit_transfer = op_submit_transfer,
2056 .cancel_transfer = op_cancel_transfer,
2057 .clear_transfer_priv = op_clear_transfer_priv,
2059 .handle_events = op_handle_events,
2061 .clock_gettime = op_clock_gettime,
2063 .device_priv_size = sizeof(struct linux_device_priv),
2064 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2065 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2066 .add_iso_packet_size = 0,