libusb 1.0.7: patches from trunk
[tomato.git] / release / src / router / libusb10 / libusb / os / linux_usbfs.c
blob5937b94b0d82e31643aa00b7cb5fdf440dd96f0d
1 /*
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
21 #include <config.h>
22 #include <ctype.h>
23 #include <dirent.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <poll.h>
27 #include <pthread.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/utsname.h>
35 #include <unistd.h>
37 #include "libusb.h"
38 #include "libusbi.h"
39 #include "linux_usbfs.h"
41 /* sysfs vs usbfs:
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 error except a
78 * cancellation, all URBs within that transfer will be cancelled with the
79 * endpoint is disabled, meaning that no more data can creep in during the
80 * time it takes to cancel the remaining URBs.
82 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
83 * (in either direction) except the first.
84 * For IN transfers, we must also set SHORT_NOT_OK on all the URBs.
85 * For OUT transfers, SHORT_NOT_OK must not be set. The effective behaviour
86 * (where an OUT transfer does not complete, the rest of the URBs in the
87 * transfer get cancelled) is already in effect, and setting this flag is
88 * disallowed (a kernel with USB debugging enabled will reject such URBs).
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 {
104 char *sysfs_dir;
105 unsigned char *dev_descriptor;
106 unsigned char *config_descriptor;
109 struct linux_device_handle_priv {
110 int fd;
113 enum reap_action {
114 NORMAL = 0,
115 /* submission failed after the first URB, so await cancellation/completion
116 * of all the others */
117 SUBMIT_FAILED,
119 /* cancelled by user or timeout */
120 CANCELLED,
122 /* completed multi-URB transfer in non-final URB */
123 COMPLETED_EARLY,
126 struct linux_transfer_priv {
127 union {
128 struct usbfs_urb *urbs;
129 struct usbfs_urb **iso_urbs;
132 enum reap_action reap_action;
133 int num_urbs;
134 unsigned int num_retired;
136 /* next iso packet in user-supplied transfer to be populated */
137 int iso_packet_offset;
140 static void __get_usbfs_path(struct libusb_device *dev, char *path)
142 snprintf(path, PATH_MAX, "%s/%03d/%03d", usbfs_path, dev->bus_number,
143 dev->device_address);
146 static struct linux_device_priv *__device_priv(struct libusb_device *dev)
148 return (struct linux_device_priv *) dev->os_priv;
151 static struct linux_device_handle_priv *__device_handle_priv(
152 struct libusb_device_handle *handle)
154 return (struct linux_device_handle_priv *) handle->os_priv;
157 static int check_usb_vfs(const char *dirname)
159 DIR *dir;
160 struct dirent *entry;
161 int found = 0;
163 dir = opendir(dirname);
164 if (!dir)
165 return 0;
167 while ((entry = readdir(dir)) != NULL) {
168 if (entry->d_name[0] == '.')
169 continue;
171 /* We assume if we find any files that it must be the right place */
172 found = 1;
173 break;
176 closedir(dir);
177 return found;
180 static const char *find_usbfs_path(void)
182 const char *path = "/dev/bus/usb";
183 const char *ret = NULL;
185 if (check_usb_vfs(path)) {
186 ret = path;
187 } else {
188 path = "/proc/bus/usb";
189 if (check_usb_vfs(path))
190 ret = path;
193 usbi_dbg("found usbfs at %s", ret);
194 return ret;
197 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
198 * seem to lack it). fall back to REALTIME if we have to. */
199 static clockid_t find_monotonic_clock(void)
201 struct timespec ts;
202 int r;
204 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
205 * because it's not available through timerfd */
206 r = clock_gettime(CLOCK_MONOTONIC, &ts);
207 if (r == 0) {
208 return CLOCK_MONOTONIC;
209 } else {
210 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
211 return CLOCK_REALTIME;
215 /* bulk continuation URB flag available from Linux 2.6.32 */
216 static int check_flag_bulk_continuation(void)
218 struct utsname uts;
219 int sublevel;
221 if (uname(&uts) < 0)
222 return -1;
223 if (strlen(uts.release) < 4)
224 return 0;
225 if (strncmp(uts.release, "2.6.", 4) != 0)
226 return 0;
228 sublevel = atoi(uts.release + 4);
229 return sublevel >= 32;
232 static int op_init(struct libusb_context *ctx)
234 struct stat statbuf;
235 int r;
237 usbfs_path = find_usbfs_path();
238 if (!usbfs_path) {
239 usbi_err(ctx, "could not find usbfs");
240 return LIBUSB_ERROR_OTHER;
243 if (monotonic_clkid == -1)
244 monotonic_clkid = find_monotonic_clock();
246 if (supports_flag_bulk_continuation == -1) {
247 supports_flag_bulk_continuation = check_flag_bulk_continuation();
248 if (supports_flag_bulk_continuation == -1) {
249 usbi_err(ctx, "error checking for bulk continuation support");
250 return LIBUSB_ERROR_OTHER;
254 if (supports_flag_bulk_continuation)
255 usbi_dbg("bulk continuation flag supported");
257 r = stat(SYSFS_DEVICE_PATH, &statbuf);
258 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
259 usbi_dbg("found usb devices in sysfs");
260 } else {
261 usbi_dbg("sysfs usb info not available");
262 sysfs_has_descriptors = 0;
263 sysfs_can_relate_devices = 0;
266 return 0;
269 static int usbfs_get_device_descriptor(struct libusb_device *dev,
270 unsigned char *buffer)
272 struct linux_device_priv *priv = __device_priv(dev);
274 /* return cached copy */
275 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
276 return 0;
279 static int __open_sysfs_attr(struct libusb_device *dev, const char *attr)
281 struct linux_device_priv *priv = __device_priv(dev);
282 char filename[PATH_MAX];
283 int fd;
285 snprintf(filename, PATH_MAX, "%s/%s/%s",
286 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
287 fd = open(filename, O_RDONLY);
288 if (fd < 0) {
289 usbi_err(DEVICE_CTX(dev),
290 "open %s failed ret=%d errno=%d", filename, fd, errno);
291 return LIBUSB_ERROR_IO;
294 return fd;
297 static int sysfs_get_device_descriptor(struct libusb_device *dev,
298 unsigned char *buffer)
300 int fd;
301 ssize_t r;
303 /* sysfs provides access to an in-memory copy of the device descriptor,
304 * so we use that rather than keeping our own copy */
306 fd = __open_sysfs_attr(dev, "descriptors");
307 if (fd < 0)
308 return fd;
310 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
311 close(fd);
312 if (r < 0) {
313 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
314 return LIBUSB_ERROR_IO;
315 } else if (r < DEVICE_DESC_LENGTH) {
316 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
317 return LIBUSB_ERROR_IO;
320 return 0;
323 static int op_get_device_descriptor(struct libusb_device *dev,
324 unsigned char *buffer, int *host_endian)
326 if (sysfs_has_descriptors) {
327 return sysfs_get_device_descriptor(dev, buffer);
328 } else {
329 *host_endian = 1;
330 return usbfs_get_device_descriptor(dev, buffer);
334 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
335 unsigned char *buffer, size_t len)
337 struct linux_device_priv *priv = __device_priv(dev);
338 if (!priv->config_descriptor)
339 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
341 /* retrieve cached copy */
342 memcpy(buffer, priv->config_descriptor, len);
343 return 0;
346 /* read the bConfigurationValue for a device */
347 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
349 char *endptr;
350 char tmp[4] = {0, 0, 0, 0};
351 long num;
352 int fd;
353 size_t r;
355 fd = __open_sysfs_attr(dev, "bConfigurationValue");
356 if (fd < 0)
357 return fd;
359 r = read(fd, tmp, sizeof(tmp));
360 close(fd);
361 if (r < 0) {
362 usbi_err(DEVICE_CTX(dev),
363 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
364 return LIBUSB_ERROR_IO;
365 } else if (r == 0) {
366 usbi_err(DEVICE_CTX(dev), "device unconfigured");
367 *config = -1;
368 return 0;
371 if (tmp[sizeof(tmp) - 1] != 0) {
372 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
373 return LIBUSB_ERROR_IO;
374 } else if (tmp[0] == 0) {
375 usbi_err(DEVICE_CTX(dev), "no configuration value?");
376 return LIBUSB_ERROR_IO;
379 num = strtol(tmp, &endptr, 10);
380 if (endptr == tmp) {
381 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
382 return LIBUSB_ERROR_IO;
385 *config = (int) num;
386 return 0;
389 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
390 * seeks to the next one. */
391 static int seek_to_next_config(struct libusb_context *ctx, int fd,
392 int host_endian)
394 struct libusb_config_descriptor config;
395 unsigned char tmp[6];
396 off_t off;
397 int r;
399 /* read first 6 bytes of descriptor */
400 r = read(fd, tmp, sizeof(tmp));
401 if (r < 0) {
402 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
403 return LIBUSB_ERROR_IO;
404 } else if (r < sizeof(tmp)) {
405 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
406 return LIBUSB_ERROR_IO;
409 /* seek forward to end of config */
410 usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
411 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
412 if (off < 0) {
413 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
414 return LIBUSB_ERROR_IO;
417 return 0;
420 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
421 unsigned char *buffer, size_t len)
423 int fd;
424 ssize_t r;
425 off_t off;
426 int to_copy;
427 int config;
428 unsigned char tmp[6];
430 r = sysfs_get_active_config(dev, &config);
431 if (r < 0)
432 return r;
433 if (config == -1)
434 return LIBUSB_ERROR_NOT_FOUND;
436 usbi_dbg("active configuration %d", config);
438 /* sysfs provides access to an in-memory copy of the device descriptor,
439 * so we use that rather than keeping our own copy */
441 fd = __open_sysfs_attr(dev, "descriptors");
442 if (fd < 0)
443 return fd;
445 /* device might have been unconfigured since we read bConfigurationValue,
446 * so first check that there is any config descriptor data at all... */
447 off = lseek(fd, 0, SEEK_END);
448 if (off < 1) {
449 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
450 off, errno);
451 close(fd);
452 return LIBUSB_ERROR_IO;
453 } else if (off == DEVICE_DESC_LENGTH) {
454 close(fd);
455 return LIBUSB_ERROR_NOT_FOUND;
458 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
459 if (off < 0) {
460 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
461 close(fd);
462 return LIBUSB_ERROR_IO;
465 /* unbounded loop: we expect the descriptor to be present under all
466 * circumstances */
467 while (1) {
468 r = read(fd, tmp, sizeof(tmp));
469 if (r < 0) {
470 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
471 fd, errno);
472 return LIBUSB_ERROR_IO;
473 } else if (r < sizeof(tmp)) {
474 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
475 return LIBUSB_ERROR_IO;
478 /* check bConfigurationValue */
479 if (tmp[5] == config)
480 break;
482 /* try the next descriptor */
483 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
484 if (off < 0)
485 return LIBUSB_ERROR_IO;
487 r = seek_to_next_config(DEVICE_CTX(dev), fd, 1);
488 if (r < 0)
489 return r;
492 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
493 memcpy(buffer, tmp, to_copy);
494 if (len > sizeof(tmp)) {
495 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
496 if (r < 0) {
497 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
498 fd, errno);
499 r = LIBUSB_ERROR_IO;
500 } else if (r == 0) {
501 usbi_dbg("device is unconfigured");
502 r = LIBUSB_ERROR_NOT_FOUND;
503 } else if (r < len - sizeof(tmp)) {
504 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
505 r = LIBUSB_ERROR_IO;
507 } else {
508 r = 0;
511 close(fd);
512 return r;
515 static int op_get_active_config_descriptor(struct libusb_device *dev,
516 unsigned char *buffer, size_t len, int *host_endian)
518 if (sysfs_has_descriptors) {
519 return sysfs_get_active_config_descriptor(dev, buffer, len);
520 } else {
521 return usbfs_get_active_config_descriptor(dev, buffer, len);
525 /* takes a usbfs fd, attempts to find the requested config and copy a certain
526 * amount of it into an output buffer. */
527 static int get_config_descriptor(struct libusb_context *ctx, int fd,
528 uint8_t config_index, unsigned char *buffer, size_t len)
530 off_t off;
531 ssize_t r;
533 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
534 if (off < 0) {
535 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
536 return LIBUSB_ERROR_IO;
539 /* might need to skip some configuration descriptors to reach the
540 * requested configuration */
541 while (config_index > 0) {
542 r = seek_to_next_config(ctx, fd, 0);
543 if (r < 0)
544 return r;
545 config_index--;
548 /* read the rest of the descriptor */
549 r = read(fd, buffer, len);
550 if (r < 0) {
551 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
552 return LIBUSB_ERROR_IO;
553 } else if (r < len) {
554 usbi_err(ctx, "short output read %d/%d", r, len);
555 return LIBUSB_ERROR_IO;
558 return 0;
561 static int op_get_config_descriptor(struct libusb_device *dev,
562 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
564 char filename[PATH_MAX];
565 int fd;
566 int r;
568 /* always read from usbfs: sysfs only has the active descriptor
569 * this will involve waking the device up, but oh well! */
571 /* FIXME: the above is no longer true, new kernels have all descriptors
572 * in the descriptors file. but its kinda hard to detect if the kernel
573 * is sufficiently new. */
575 __get_usbfs_path(dev, filename);
576 fd = open(filename, O_RDONLY);
577 if (fd < 0) {
578 usbi_err(DEVICE_CTX(dev),
579 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
580 return LIBUSB_ERROR_IO;
583 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
584 close(fd);
585 return r;
588 /* cache the active config descriptor in memory. a value of -1 means that
589 * we aren't sure which one is active, so just assume the first one.
590 * only for usbfs. */
591 static int cache_active_config(struct libusb_device *dev, int fd,
592 int active_config)
594 struct linux_device_priv *priv = __device_priv(dev);
595 struct libusb_config_descriptor config;
596 unsigned char tmp[8];
597 unsigned char *buf;
598 int idx;
599 int r;
601 if (active_config == -1) {
602 idx = 0;
603 } else {
604 r = usbi_get_config_index_by_value(dev, active_config, &idx);
605 if (r < 0)
606 return r;
607 if (idx == -1)
608 return LIBUSB_ERROR_NOT_FOUND;
611 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
612 if (r < 0) {
613 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
614 return r;
617 usbi_parse_descriptor(tmp, "bbw", &config, 0);
618 buf = malloc(config.wTotalLength);
619 if (!buf)
620 return LIBUSB_ERROR_NO_MEM;
622 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
623 config.wTotalLength);
624 if (r < 0) {
625 free(buf);
626 return r;
629 if (priv->config_descriptor)
630 free(priv->config_descriptor);
631 priv->config_descriptor = buf;
632 return 0;
635 /* send a control message to retrieve active configuration */
636 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
638 unsigned char active_config = 0;
639 int r;
641 struct usbfs_ctrltransfer ctrl = {
642 .bmRequestType = LIBUSB_ENDPOINT_IN,
643 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
644 .wValue = 0,
645 .wIndex = 0,
646 .wLength = 1,
647 .timeout = 1000,
648 .data = &active_config
651 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
652 if (r < 0) {
653 if (errno == ENODEV)
654 return LIBUSB_ERROR_NO_DEVICE;
656 /* we hit this error path frequently with buggy devices :( */
657 usbi_warn(DEVICE_CTX(dev),
658 "get_configuration failed ret=%d errno=%d", r, errno);
659 return LIBUSB_ERROR_IO;
662 return active_config;
665 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
666 uint8_t devaddr, const char *sysfs_dir)
668 struct linux_device_priv *priv = __device_priv(dev);
669 unsigned char *dev_buf;
670 char path[PATH_MAX];
671 int fd;
672 int active_config = 0;
673 int device_configured = 1;
674 ssize_t r;
676 dev->bus_number = busnum;
677 dev->device_address = devaddr;
679 if (sysfs_dir) {
680 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
681 if (!priv->sysfs_dir)
682 return LIBUSB_ERROR_NO_MEM;
683 strcpy(priv->sysfs_dir, sysfs_dir);
686 if (sysfs_has_descriptors)
687 return 0;
689 /* cache device descriptor in memory so that we can retrieve it later
690 * without waking the device up (op_get_device_descriptor) */
692 priv->dev_descriptor = NULL;
693 priv->config_descriptor = NULL;
695 if (sysfs_can_relate_devices) {
696 int tmp = sysfs_get_active_config(dev, &active_config);
697 if (tmp < 0)
698 return tmp;
699 if (active_config == -1)
700 device_configured = 0;
703 __get_usbfs_path(dev, path);
704 fd = open(path, O_RDWR);
705 if (fd < 0 && errno == EACCES) {
706 fd = open(path, O_RDONLY);
707 /* if we only have read-only access to the device, we cannot
708 * send a control message to determine the active config. just
709 * assume the first one is active. */
710 active_config = -1;
713 if (fd < 0) {
714 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
715 return LIBUSB_ERROR_IO;
718 if (!sysfs_can_relate_devices) {
719 if (active_config == -1) {
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. */
723 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
724 "determine active configuration descriptor", path);
725 } else {
726 active_config = usbfs_get_active_config(dev, fd);
727 if (active_config == LIBUSB_ERROR_IO) {
728 /* buggy devices sometimes fail to report their active config.
729 * assume unconfigured and continue the probing */
730 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
731 "configuration, assumung unconfigured");
732 device_configured = 0;
733 } else if (active_config < 0) {
734 close(fd);
735 return active_config;
736 } else if (active_config == 0) {
737 /* some buggy devices have a configuration 0, but we're
738 * reaching into the corner of a corner case here, so let's
739 * not support buggy devices in these circumstances.
740 * stick to the specs: a configuration value of 0 means
741 * unconfigured. */
742 usbi_dbg("active cfg 0? assuming unconfigured device");
743 device_configured = 0;
748 dev_buf = malloc(DEVICE_DESC_LENGTH);
749 if (!dev_buf) {
750 close(fd);
751 return LIBUSB_ERROR_NO_MEM;
754 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
755 if (r < 0) {
756 usbi_err(DEVICE_CTX(dev),
757 "read descriptor failed ret=%d errno=%d", fd, errno);
758 free(dev_buf);
759 close(fd);
760 return LIBUSB_ERROR_IO;
761 } else if (r < DEVICE_DESC_LENGTH) {
762 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
763 free(dev_buf);
764 close(fd);
765 return LIBUSB_ERROR_IO;
768 /* bit of a hack: set num_configurations now because cache_active_config()
769 * calls usbi_get_config_index_by_value() which uses it */
770 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
772 if (device_configured) {
773 r = cache_active_config(dev, fd, active_config);
774 if (r < 0) {
775 close(fd);
776 free(dev_buf);
777 return r;
781 close(fd);
782 priv->dev_descriptor = dev_buf;
783 return 0;
786 static int enumerate_device(struct libusb_context *ctx,
787 struct discovered_devs **_discdevs, uint8_t busnum, uint8_t devaddr,
788 const char *sysfs_dir)
790 struct discovered_devs *discdevs;
791 unsigned long session_id;
792 int need_unref = 0;
793 struct libusb_device *dev;
794 int r = 0;
796 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
797 * will be reused. instead we should add a simple sysfs attribute with
798 * a session ID. */
799 session_id = busnum << 8 | devaddr;
800 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
801 session_id);
803 dev = usbi_get_device_by_session_id(ctx, session_id);
804 if (dev) {
805 usbi_dbg("using existing device for %d/%d (session %ld)",
806 busnum, devaddr, session_id);
807 } else {
808 usbi_dbg("allocating new device for %d/%d (session %ld)",
809 busnum, devaddr, session_id);
810 dev = usbi_alloc_device(ctx, session_id);
811 if (!dev)
812 return LIBUSB_ERROR_NO_MEM;
813 need_unref = 1;
814 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
815 if (r < 0)
816 goto out;
817 r = usbi_sanitize_device(dev);
818 if (r < 0)
819 goto out;
822 discdevs = discovered_devs_append(*_discdevs, dev);
823 if (!discdevs)
824 r = LIBUSB_ERROR_NO_MEM;
825 else
826 *_discdevs = discdevs;
828 out:
829 if (need_unref)
830 libusb_unref_device(dev);
831 return r;
834 /* open a bus directory and adds all discovered devices to discdevs. on
835 * failure (non-zero return) the pre-existing discdevs should be destroyed
836 * (and devices freed). on success, the new discdevs pointer should be used
837 * as it may have been moved. */
838 static int usbfs_scan_busdir(struct libusb_context *ctx,
839 struct discovered_devs **_discdevs, uint8_t busnum)
841 DIR *dir;
842 char dirpath[PATH_MAX];
843 struct dirent *entry;
844 struct discovered_devs *discdevs = *_discdevs;
845 int r = 0;
847 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
848 usbi_dbg("%s", dirpath);
849 dir = opendir(dirpath);
850 if (!dir) {
851 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
852 /* FIXME: should handle valid race conditions like hub unplugged
853 * during directory iteration - this is not an error */
854 return LIBUSB_ERROR_IO;
857 while ((entry = readdir(dir))) {
858 int devaddr;
860 if (entry->d_name[0] == '.')
861 continue;
863 devaddr = atoi(entry->d_name);
864 if (devaddr == 0) {
865 usbi_dbg("unknown dir entry %s", entry->d_name);
866 continue;
869 r = enumerate_device(ctx, &discdevs, busnum, (uint8_t) devaddr, NULL);
870 if (r < 0)
871 goto out;
874 *_discdevs = discdevs;
875 out:
876 closedir(dir);
877 return r;
880 static int usbfs_get_device_list(struct libusb_context *ctx,
881 struct discovered_devs **_discdevs)
883 struct dirent *entry;
884 DIR *buses = opendir(usbfs_path);
885 struct discovered_devs *discdevs = *_discdevs;
886 int r = 0;
888 if (!buses) {
889 usbi_err(ctx, "opendir buses failed errno=%d", errno);
890 return LIBUSB_ERROR_IO;
893 while ((entry = readdir(buses))) {
894 struct discovered_devs *discdevs_new = discdevs;
895 int busnum;
897 if (entry->d_name[0] == '.')
898 continue;
900 busnum = atoi(entry->d_name);
901 if (busnum == 0) {
902 usbi_dbg("unknown dir entry %s", entry->d_name);
903 continue;
906 r = usbfs_scan_busdir(ctx, &discdevs_new, busnum);
907 if (r < 0)
908 goto out;
909 discdevs = discdevs_new;
912 out:
913 closedir(buses);
914 *_discdevs = discdevs;
915 return r;
919 static int sysfs_scan_device(struct libusb_context *ctx,
920 struct discovered_devs **_discdevs, const char *devname,
921 int *usbfs_fallback)
923 int r;
924 FILE *fd;
925 char filename[PATH_MAX];
926 int busnum;
927 int devaddr;
929 usbi_dbg("scan %s", devname);
931 /* determine descriptors presence ahead of time, we need to know this
932 * when we reach initialize_device */
933 if (sysfs_has_descriptors == -1) {
934 struct stat statbuf;
936 snprintf(filename, PATH_MAX, "%s/%s/descriptors", SYSFS_DEVICE_PATH,
937 devname);
938 r = stat(filename, &statbuf);
939 if (r == 0 && S_ISREG(statbuf.st_mode)) {
940 usbi_dbg("sysfs descriptors available");
941 sysfs_has_descriptors = 1;
942 } else {
943 usbi_dbg("sysfs descriptors not available");
944 sysfs_has_descriptors = 0;
948 snprintf(filename, PATH_MAX, "%s/%s/busnum", SYSFS_DEVICE_PATH, devname);
949 fd = fopen(filename, "r");
950 if (!fd) {
951 if (errno == ENOENT) {
952 usbi_dbg("busnum not found, cannot relate sysfs to usbfs, "
953 "falling back on pure usbfs");
954 sysfs_can_relate_devices = 0;
955 *usbfs_fallback = 1;
956 return LIBUSB_ERROR_OTHER;
958 usbi_err(ctx, "open busnum failed, errno=%d", errno);
959 return LIBUSB_ERROR_IO;
962 sysfs_can_relate_devices = 1;
964 r = fscanf(fd, "%d", &busnum);
965 fclose(fd);
966 if (r != 1) {
967 usbi_err(ctx, "fscanf busnum returned %d, errno=%d", r, errno);
968 return LIBUSB_ERROR_IO;
971 snprintf(filename, PATH_MAX, "%s/%s/devnum", SYSFS_DEVICE_PATH, devname);
972 fd = fopen(filename, "r");
973 if (!fd) {
974 usbi_err(ctx, "open devnum failed, errno=%d", errno);
975 return LIBUSB_ERROR_IO;
978 r = fscanf(fd, "%d", &devaddr);
979 fclose(fd);
980 if (r != 1) {
981 usbi_err(ctx, "fscanf devnum returned %d, errno=%d", r, errno);
982 return LIBUSB_ERROR_IO;
985 usbi_dbg("bus=%d dev=%d", busnum, devaddr);
986 if (busnum > 255 || devaddr > 255)
987 return LIBUSB_ERROR_INVALID_PARAM;
989 return enumerate_device(ctx, _discdevs, busnum & 0xff, devaddr & 0xff,
990 devname);
993 static int sysfs_get_device_list(struct libusb_context *ctx,
994 struct discovered_devs **_discdevs, int *usbfs_fallback)
996 struct discovered_devs *discdevs = *_discdevs;
997 DIR *devices = opendir(SYSFS_DEVICE_PATH);
998 struct dirent *entry;
999 int r = 0;
1001 if (!devices) {
1002 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1003 return LIBUSB_ERROR_IO;
1006 while ((entry = readdir(devices))) {
1007 struct discovered_devs *discdevs_new = discdevs;
1009 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1010 || strchr(entry->d_name, ':'))
1011 continue;
1013 r = sysfs_scan_device(ctx, &discdevs_new, entry->d_name,
1014 usbfs_fallback);
1015 if (r < 0)
1016 goto out;
1017 discdevs = discdevs_new;
1020 out:
1021 closedir(devices);
1022 *_discdevs = discdevs;
1023 return r;
1026 static int op_get_device_list(struct libusb_context *ctx,
1027 struct discovered_devs **_discdevs)
1029 /* we can retrieve device list and descriptors from sysfs or usbfs.
1030 * sysfs is preferable, because if we use usbfs we end up resuming
1031 * any autosuspended USB devices. however, sysfs is not available
1032 * everywhere, so we need a usbfs fallback too.
1034 * as described in the "sysfs vs usbfs" comment, sometimes we have
1035 * sysfs but not enough information to relate sysfs devices to usbfs
1036 * nodes. the usbfs_fallback variable is used to indicate that we should
1037 * fall back on usbfs.
1039 if (sysfs_can_relate_devices != 0) {
1040 int usbfs_fallback = 0;
1041 int r = sysfs_get_device_list(ctx, _discdevs, &usbfs_fallback);
1042 if (!usbfs_fallback)
1043 return r;
1046 return usbfs_get_device_list(ctx, _discdevs);
1049 static int op_open(struct libusb_device_handle *handle)
1051 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
1052 char filename[PATH_MAX];
1054 __get_usbfs_path(handle->dev, filename);
1055 hpriv->fd = open(filename, O_RDWR);
1056 if (hpriv->fd < 0) {
1057 if (errno == EACCES) {
1058 fprintf(stderr, "libusb couldn't open USB device %s: "
1059 "Permission denied.\n"
1060 "libusb requires write access to USB device nodes.\n",
1061 filename);
1062 return LIBUSB_ERROR_ACCESS;
1063 } else if (errno == ENOENT) {
1064 return LIBUSB_ERROR_NO_DEVICE;
1065 } else {
1066 usbi_err(HANDLE_CTX(handle),
1067 "open failed, code %d errno %d", hpriv->fd, errno);
1068 return LIBUSB_ERROR_IO;
1072 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1075 static void op_close(struct libusb_device_handle *dev_handle)
1077 int fd = __device_handle_priv(dev_handle)->fd;
1078 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1079 close(fd);
1082 static int op_get_configuration(struct libusb_device_handle *handle,
1083 int *config)
1085 int r;
1086 if (sysfs_can_relate_devices != 1)
1087 return LIBUSB_ERROR_NOT_SUPPORTED;
1089 r = sysfs_get_active_config(handle->dev, config);
1090 if (*config == -1)
1091 *config = 0;
1093 return 0;
1096 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1098 struct linux_device_priv *priv = __device_priv(handle->dev);
1099 int fd = __device_handle_priv(handle)->fd;
1100 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1101 if (r) {
1102 if (errno == EINVAL)
1103 return LIBUSB_ERROR_NOT_FOUND;
1104 else if (errno == EBUSY)
1105 return LIBUSB_ERROR_BUSY;
1106 else if (errno == ENODEV)
1107 return LIBUSB_ERROR_NO_DEVICE;
1109 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1110 return LIBUSB_ERROR_OTHER;
1113 if (!sysfs_has_descriptors) {
1114 /* update our cached active config descriptor */
1115 if (config == -1) {
1116 if (priv->config_descriptor) {
1117 free(priv->config_descriptor);
1118 priv->config_descriptor = NULL;
1120 } else {
1121 r = cache_active_config(handle->dev, fd, config);
1122 if (r < 0)
1123 usbi_warn(HANDLE_CTX(handle),
1124 "failed to update cached config descriptor, error %d", r);
1128 return 0;
1131 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1133 int fd = __device_handle_priv(handle)->fd;
1134 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1135 if (r) {
1136 if (errno == ENOENT)
1137 return LIBUSB_ERROR_NOT_FOUND;
1138 else if (errno == EBUSY)
1139 return LIBUSB_ERROR_BUSY;
1140 else if (errno == ENODEV)
1141 return LIBUSB_ERROR_NO_DEVICE;
1143 usbi_err(HANDLE_CTX(handle),
1144 "claim interface failed, error %d errno %d", r, errno);
1145 return LIBUSB_ERROR_OTHER;
1147 return 0;
1150 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1152 int fd = __device_handle_priv(handle)->fd;
1153 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1154 if (r) {
1155 if (errno == ENODEV)
1156 return LIBUSB_ERROR_NO_DEVICE;
1158 usbi_err(HANDLE_CTX(handle),
1159 "release interface failed, error %d errno %d", r, errno);
1160 return LIBUSB_ERROR_OTHER;
1162 return 0;
1165 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1166 int altsetting)
1168 int fd = __device_handle_priv(handle)->fd;
1169 struct usbfs_setinterface setintf;
1170 int r;
1172 setintf.interface = iface;
1173 setintf.altsetting = altsetting;
1174 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1175 if (r) {
1176 if (errno == EINVAL)
1177 return LIBUSB_ERROR_NOT_FOUND;
1178 else if (errno == ENODEV)
1179 return LIBUSB_ERROR_NO_DEVICE;
1181 usbi_err(HANDLE_CTX(handle),
1182 "setintf failed error %d errno %d", r, errno);
1183 return LIBUSB_ERROR_OTHER;
1186 return 0;
1189 static int op_clear_halt(struct libusb_device_handle *handle,
1190 unsigned char endpoint)
1192 int fd = __device_handle_priv(handle)->fd;
1193 unsigned int _endpoint = endpoint;
1194 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1195 if (r) {
1196 if (errno == ENOENT)
1197 return LIBUSB_ERROR_NOT_FOUND;
1198 else if (errno == ENODEV)
1199 return LIBUSB_ERROR_NO_DEVICE;
1201 usbi_err(HANDLE_CTX(handle),
1202 "clear_halt failed error %d errno %d", r, errno);
1203 return LIBUSB_ERROR_OTHER;
1206 return 0;
1209 static int op_reset_device(struct libusb_device_handle *handle)
1211 int fd = __device_handle_priv(handle)->fd;
1212 int r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1213 if (r) {
1214 if (errno == ENODEV)
1215 return LIBUSB_ERROR_NOT_FOUND;
1217 usbi_err(HANDLE_CTX(handle),
1218 "reset failed error %d errno %d", r, errno);
1219 return LIBUSB_ERROR_OTHER;
1222 return 0;
1225 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1226 int interface)
1228 int fd = __device_handle_priv(handle)->fd;
1229 struct usbfs_getdriver getdrv;
1230 int r;
1232 getdrv.interface = interface;
1233 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1234 if (r) {
1235 if (errno == ENODATA)
1236 return 0;
1237 else if (errno == ENODEV)
1238 return LIBUSB_ERROR_NO_DEVICE;
1240 usbi_err(HANDLE_CTX(handle),
1241 "get driver failed error %d errno %d", r, errno);
1242 return LIBUSB_ERROR_OTHER;
1245 return 1;
1248 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1249 int interface)
1251 int fd = __device_handle_priv(handle)->fd;
1252 struct usbfs_ioctl command;
1253 int r;
1255 command.ifno = interface;
1256 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1257 command.data = NULL;
1259 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1260 if (r) {
1261 if (errno == ENODATA)
1262 return LIBUSB_ERROR_NOT_FOUND;
1263 else if (errno == EINVAL)
1264 return LIBUSB_ERROR_INVALID_PARAM;
1265 else if (errno == ENODEV)
1266 return LIBUSB_ERROR_NO_DEVICE;
1268 usbi_err(HANDLE_CTX(handle),
1269 "detach failed error %d errno %d", r, errno);
1270 return LIBUSB_ERROR_OTHER;
1273 return 0;
1276 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1277 int interface)
1279 int fd = __device_handle_priv(handle)->fd;
1280 struct usbfs_ioctl command;
1281 int r;
1283 command.ifno = interface;
1284 command.ioctl_code = IOCTL_USBFS_CONNECT;
1285 command.data = NULL;
1287 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1288 if (r < 0) {
1289 if (errno == ENODATA)
1290 return LIBUSB_ERROR_NOT_FOUND;
1291 else if (errno == EINVAL)
1292 return LIBUSB_ERROR_INVALID_PARAM;
1293 else if (errno == ENODEV)
1294 return LIBUSB_ERROR_NO_DEVICE;
1295 else if (errno == EBUSY)
1296 return LIBUSB_ERROR_BUSY;
1298 usbi_err(HANDLE_CTX(handle),
1299 "attach failed error %d errno %d", r, errno);
1300 return LIBUSB_ERROR_OTHER;
1301 } else if (r == 0) {
1302 return LIBUSB_ERROR_NOT_FOUND;
1305 return 0;
1308 static void op_destroy_device(struct libusb_device *dev)
1310 struct linux_device_priv *priv = __device_priv(dev);
1311 if (!sysfs_has_descriptors) {
1312 if (priv->dev_descriptor)
1313 free(priv->dev_descriptor);
1314 if (priv->config_descriptor)
1315 free(priv->config_descriptor);
1317 if (priv->sysfs_dir)
1318 free(priv->sysfs_dir);
1321 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1323 int i;
1324 for (i = 0; i < tpriv->num_urbs; i++) {
1325 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1326 if (!urb)
1327 break;
1328 free(urb);
1331 free(tpriv->iso_urbs);
1332 tpriv->iso_urbs = NULL;
1335 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1336 unsigned char urb_type)
1338 struct libusb_transfer *transfer =
1339 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1340 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1341 struct linux_device_handle_priv *dpriv =
1342 __device_handle_priv(transfer->dev_handle);
1343 struct usbfs_urb *urbs;
1344 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1345 == LIBUSB_ENDPOINT_OUT;
1346 int r;
1347 int i;
1348 size_t alloc_size;
1350 if (tpriv->urbs)
1351 return LIBUSB_ERROR_BUSY;
1353 /* usbfs places a 16kb limit on bulk URBs. we divide up larger requests
1354 * into smaller units to meet such restriction, then fire off all the
1355 * units at once. it would be simpler if we just fired one unit at a time,
1356 * but there is a big performance gain through doing it this way. */
1357 int num_urbs = transfer->length / MAX_BULK_BUFFER_LENGTH;
1358 int last_urb_partial = 0;
1360 if (transfer->length == 0) {
1361 num_urbs = 1;
1362 } else if ((transfer->length % MAX_BULK_BUFFER_LENGTH) > 0) {
1363 last_urb_partial = 1;
1364 num_urbs++;
1366 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1367 transfer->length);
1368 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1369 urbs = malloc(alloc_size);
1370 if (!urbs)
1371 return LIBUSB_ERROR_NO_MEM;
1372 memset(urbs, 0, alloc_size);
1373 tpriv->urbs = urbs;
1374 tpriv->num_urbs = num_urbs;
1375 tpriv->num_retired = 0;
1376 tpriv->reap_action = NORMAL;
1378 for (i = 0; i < num_urbs; i++) {
1379 struct usbfs_urb *urb = &urbs[i];
1380 urb->usercontext = itransfer;
1381 urb->type = urb_type;
1382 urb->endpoint = transfer->endpoint;
1383 urb->buffer = transfer->buffer + (i * MAX_BULK_BUFFER_LENGTH);
1384 if (supports_flag_bulk_continuation && !is_out)
1385 urb->flags = USBFS_URB_SHORT_NOT_OK;
1386 if (i == num_urbs - 1 && last_urb_partial)
1387 urb->buffer_length = transfer->length % MAX_BULK_BUFFER_LENGTH;
1388 else if (transfer->length == 0)
1389 urb->buffer_length = 0;
1390 else
1391 urb->buffer_length = MAX_BULK_BUFFER_LENGTH;
1393 if (i > 0 && supports_flag_bulk_continuation)
1394 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1396 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1397 if (r < 0) {
1398 int j;
1400 if (errno == ENODEV) {
1401 r = LIBUSB_ERROR_NO_DEVICE;
1402 } else {
1403 usbi_err(TRANSFER_CTX(transfer),
1404 "submiturb failed error %d errno=%d", r, errno);
1405 r = LIBUSB_ERROR_IO;
1408 /* if the first URB submission fails, we can simply free up and
1409 * return failure immediately. */
1410 if (i == 0) {
1411 usbi_dbg("first URB failed, easy peasy");
1412 free(urbs);
1413 tpriv->urbs = NULL;
1414 return r;
1417 /* if it's not the first URB that failed, the situation is a bit
1418 * tricky. we must discard all previous URBs. there are
1419 * complications:
1420 * - discarding is asynchronous - discarded urbs will be reaped
1421 * later. the user must not have freed the transfer when the
1422 * discarded URBs are reaped, otherwise libusb will be using
1423 * freed memory.
1424 * - the earlier URBs may have completed successfully and we do
1425 * not want to throw away any data.
1426 * so, in this case we discard all the previous URBs BUT we report
1427 * that the transfer was submitted successfully. then later when
1428 * the final discard completes we can report error to the user.
1430 tpriv->reap_action = SUBMIT_FAILED;
1432 /* The URBs we haven't submitted yet we count as already
1433 * retired. */
1434 tpriv->num_retired += num_urbs - i;
1435 for (j = 0; j < i; j++) {
1436 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &urbs[j]);
1437 if (tmp && errno != EINVAL)
1438 usbi_warn(TRANSFER_CTX(transfer),
1439 "unrecognised discard errno %d", errno);
1442 usbi_dbg("reporting successful submission but waiting for %d "
1443 "discards before reporting error", i);
1444 return 0;
1448 return 0;
1451 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1453 struct libusb_transfer *transfer =
1454 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1455 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1456 struct linux_device_handle_priv *dpriv =
1457 __device_handle_priv(transfer->dev_handle);
1458 struct usbfs_urb **urbs;
1459 size_t alloc_size;
1460 int num_packets = transfer->num_iso_packets;
1461 int i;
1462 int this_urb_len = 0;
1463 int num_urbs = 1;
1464 int packet_offset = 0;
1465 unsigned int packet_len;
1466 unsigned char *urb_buffer = transfer->buffer;
1468 if (tpriv->iso_urbs)
1469 return LIBUSB_ERROR_BUSY;
1471 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1472 * into smaller units to meet such restriction, then fire off all the
1473 * units at once. it would be simpler if we just fired one unit at a time,
1474 * but there is a big performance gain through doing it this way. */
1476 /* calculate how many URBs we need */
1477 for (i = 0; i < num_packets; i++) {
1478 int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1479 packet_len = transfer->iso_packet_desc[i].length;
1481 if (packet_len > space_remaining) {
1482 num_urbs++;
1483 this_urb_len = packet_len;
1484 } else {
1485 this_urb_len += packet_len;
1488 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1490 alloc_size = num_urbs * sizeof(*urbs);
1491 urbs = malloc(alloc_size);
1492 if (!urbs)
1493 return LIBUSB_ERROR_NO_MEM;
1494 memset(urbs, 0, alloc_size);
1496 tpriv->iso_urbs = urbs;
1497 tpriv->num_urbs = num_urbs;
1498 tpriv->num_retired = 0;
1499 tpriv->reap_action = NORMAL;
1500 tpriv->iso_packet_offset = 0;
1502 /* allocate + initialize each URB with the correct number of packets */
1503 for (i = 0; i < num_urbs; i++) {
1504 struct usbfs_urb *urb;
1505 int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1506 int urb_packet_offset = 0;
1507 unsigned char *urb_buffer_orig = urb_buffer;
1508 int j;
1509 int k;
1511 /* swallow up all the packets we can fit into this URB */
1512 while (packet_offset < transfer->num_iso_packets) {
1513 packet_len = transfer->iso_packet_desc[packet_offset].length;
1514 if (packet_len <= space_remaining_in_urb) {
1515 /* throw it in */
1516 urb_packet_offset++;
1517 packet_offset++;
1518 space_remaining_in_urb -= packet_len;
1519 urb_buffer += packet_len;
1520 } else {
1521 /* it can't fit, save it for the next URB */
1522 break;
1526 alloc_size = sizeof(*urb)
1527 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1528 urb = malloc(alloc_size);
1529 if (!urb) {
1530 free_iso_urbs(tpriv);
1531 return LIBUSB_ERROR_NO_MEM;
1533 memset(urb, 0, alloc_size);
1534 urbs[i] = urb;
1536 /* populate packet lengths */
1537 for (j = 0, k = packet_offset - urb_packet_offset;
1538 k < packet_offset; k++, j++) {
1539 packet_len = transfer->iso_packet_desc[k].length;
1540 urb->iso_frame_desc[j].length = packet_len;
1543 urb->usercontext = itransfer;
1544 urb->type = USBFS_URB_TYPE_ISO;
1545 /* FIXME: interface for non-ASAP data? */
1546 urb->flags = USBFS_URB_ISO_ASAP;
1547 urb->endpoint = transfer->endpoint;
1548 urb->number_of_packets = urb_packet_offset;
1549 urb->buffer = urb_buffer_orig;
1552 /* submit URBs */
1553 for (i = 0; i < num_urbs; i++) {
1554 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1555 if (r < 0) {
1556 int j;
1558 if (errno == ENODEV) {
1559 r = LIBUSB_ERROR_NO_DEVICE;
1560 } else {
1561 usbi_err(TRANSFER_CTX(transfer),
1562 "submiturb failed error %d errno=%d", r, errno);
1563 r = LIBUSB_ERROR_IO;
1566 /* if the first URB submission fails, we can simply free up and
1567 * return failure immediately. */
1568 if (i == 0) {
1569 usbi_dbg("first URB failed, easy peasy");
1570 free_iso_urbs(tpriv);
1571 return r;
1574 /* if it's not the first URB that failed, the situation is a bit
1575 * tricky. we must discard all previous URBs. there are
1576 * complications:
1577 * - discarding is asynchronous - discarded urbs will be reaped
1578 * later. the user must not have freed the transfer when the
1579 * discarded URBs are reaped, otherwise libusb will be using
1580 * freed memory.
1581 * - the earlier URBs may have completed successfully and we do
1582 * not want to throw away any data.
1583 * so, in this case we discard all the previous URBs BUT we report
1584 * that the transfer was submitted successfully. then later when
1585 * the final discard completes we can report error to the user.
1587 tpriv->reap_action = SUBMIT_FAILED;
1589 /* The URBs we haven't submitted yet we count as already
1590 * retired. */
1591 tpriv->num_retired = num_urbs - i;
1592 for (j = 0; j < i; j++) {
1593 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urbs[j]);
1594 if (tmp && errno != EINVAL)
1595 usbi_warn(TRANSFER_CTX(transfer),
1596 "unrecognised discard errno %d", errno);
1599 usbi_dbg("reporting successful submission but waiting for %d "
1600 "discards before reporting error", i);
1601 return 0;
1605 return 0;
1608 static int submit_control_transfer(struct usbi_transfer *itransfer)
1610 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1611 struct libusb_transfer *transfer =
1612 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1613 struct linux_device_handle_priv *dpriv =
1614 __device_handle_priv(transfer->dev_handle);
1615 struct usbfs_urb *urb;
1616 int r;
1618 if (tpriv->urbs)
1619 return LIBUSB_ERROR_BUSY;
1621 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1622 return LIBUSB_ERROR_INVALID_PARAM;
1624 urb = malloc(sizeof(struct usbfs_urb));
1625 if (!urb)
1626 return LIBUSB_ERROR_NO_MEM;
1627 memset(urb, 0, sizeof(struct usbfs_urb));
1628 tpriv->urbs = urb;
1629 tpriv->reap_action = NORMAL;
1631 urb->usercontext = itransfer;
1632 urb->type = USBFS_URB_TYPE_CONTROL;
1633 urb->endpoint = transfer->endpoint;
1634 urb->buffer = transfer->buffer;
1635 urb->buffer_length = transfer->length;
1637 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1638 if (r < 0) {
1639 free(urb);
1640 tpriv->urbs = NULL;
1641 if (errno == ENODEV)
1642 return LIBUSB_ERROR_NO_DEVICE;
1644 usbi_err(TRANSFER_CTX(transfer),
1645 "submiturb failed error %d errno=%d", r, errno);
1646 return LIBUSB_ERROR_IO;
1648 return 0;
1651 static int op_submit_transfer(struct usbi_transfer *itransfer)
1653 struct libusb_transfer *transfer =
1654 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1656 switch (transfer->type) {
1657 case LIBUSB_TRANSFER_TYPE_CONTROL:
1658 return submit_control_transfer(itransfer);
1659 case LIBUSB_TRANSFER_TYPE_BULK:
1660 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1661 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1662 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1663 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1664 return submit_iso_transfer(itransfer);
1665 default:
1666 usbi_err(TRANSFER_CTX(transfer),
1667 "unknown endpoint type %d", transfer->type);
1668 return LIBUSB_ERROR_INVALID_PARAM;
1672 static int cancel_control_transfer(struct usbi_transfer *itransfer)
1674 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1675 struct libusb_transfer *transfer =
1676 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1677 struct linux_device_handle_priv *dpriv =
1678 __device_handle_priv(transfer->dev_handle);
1679 int r;
1681 if (!tpriv->urbs)
1682 return LIBUSB_ERROR_NOT_FOUND;
1684 tpriv->reap_action = CANCELLED;
1685 r = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->urbs);
1686 if(r) {
1687 if (errno == EINVAL) {
1688 usbi_dbg("URB not found --> assuming ready to be reaped");
1689 return 0;
1690 } else {
1691 usbi_err(TRANSFER_CTX(transfer),
1692 "unrecognised DISCARD code %d", errno);
1693 return LIBUSB_ERROR_OTHER;
1697 return 0;
1700 static int cancel_bulk_transfer(struct usbi_transfer *itransfer)
1702 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1703 struct libusb_transfer *transfer =
1704 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1705 struct linux_device_handle_priv *dpriv =
1706 __device_handle_priv(transfer->dev_handle);
1707 int i;
1709 if (!tpriv->urbs)
1710 return LIBUSB_ERROR_NOT_FOUND;
1712 tpriv->reap_action = CANCELLED;
1713 for (i = 0; i < tpriv->num_urbs; i++) {
1714 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1715 if (tmp && errno != EINVAL)
1716 usbi_warn(TRANSFER_CTX(transfer),
1717 "unrecognised discard errno %d", errno);
1719 return 0;
1722 static int cancel_iso_transfer(struct usbi_transfer *itransfer)
1724 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1725 struct libusb_transfer *transfer =
1726 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1727 struct linux_device_handle_priv *dpriv =
1728 __device_handle_priv(transfer->dev_handle);
1729 int i;
1731 if (!tpriv->iso_urbs)
1732 return LIBUSB_ERROR_NOT_FOUND;
1734 tpriv->reap_action = CANCELLED;
1735 for (i = 0; i < tpriv->num_urbs; i++) {
1736 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->iso_urbs[i]);
1737 if (tmp && errno != EINVAL)
1738 usbi_warn(TRANSFER_CTX(transfer),
1739 "unrecognised discard errno %d", errno);
1741 return 0;
1744 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1746 struct libusb_transfer *transfer =
1747 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1749 switch (transfer->type) {
1750 case LIBUSB_TRANSFER_TYPE_CONTROL:
1751 return cancel_control_transfer(itransfer);
1752 case LIBUSB_TRANSFER_TYPE_BULK:
1753 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1754 return cancel_bulk_transfer(itransfer);
1755 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1756 return cancel_iso_transfer(itransfer);
1757 default:
1758 usbi_err(TRANSFER_CTX(transfer),
1759 "unknown endpoint type %d", transfer->type);
1760 return LIBUSB_ERROR_INVALID_PARAM;
1764 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1766 struct libusb_transfer *transfer =
1767 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1768 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1770 switch (transfer->type) {
1771 case LIBUSB_TRANSFER_TYPE_CONTROL:
1772 case LIBUSB_TRANSFER_TYPE_BULK:
1773 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1774 free(tpriv->urbs);
1775 tpriv->urbs = NULL;
1776 break;
1777 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1778 free_iso_urbs(tpriv);
1779 break;
1780 default:
1781 usbi_err(TRANSFER_CTX(transfer),
1782 "unknown endpoint type %d", transfer->type);
1786 static int handle_bulk_completion(struct usbi_transfer *itransfer,
1787 struct usbfs_urb *urb)
1789 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1790 int num_urbs = tpriv->num_urbs;
1791 int urb_idx = urb - tpriv->urbs;
1792 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
1793 int r = 0;
1795 pthread_mutex_lock(&itransfer->lock);
1796 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1797 urb_idx + 1, num_urbs);
1799 tpriv->num_retired++;
1801 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
1802 /* Workaround for 2.4 UHCI interrupt transfers */
1803 if ((urb->status == -ECONNABORTED || urb->status == -ECONNRESET) &&
1804 urb->type == USBFS_URB_TYPE_INTERRUPT &&
1805 urb->actual_length > 0) {
1806 urb->status = 0;
1808 #endif
1810 if (tpriv->reap_action != NORMAL) {
1811 /* cancelled, submit_fail, or completed early */
1812 usbi_dbg("abnormal reap: urb status %d", urb->status);
1814 /* even though we're in the process of cancelling, it's possible that
1815 * we may receive some data in these URBs that we don't want to lose.
1816 * examples:
1817 * 1. while the kernel is cancelling all the packets that make up an
1818 * URB, a few of them might complete. so we get back a successful
1819 * cancellation *and* some data.
1820 * 2. we receive a short URB which marks the early completion condition,
1821 * so we start cancelling the remaining URBs. however, we're too
1822 * slow and another URB completes (or at least completes partially).
1824 * When this happens, our objectives are not to lose any "surplus" data,
1825 * and also to stick it at the end of the previously-received data
1826 * (closing any holes), so that libusb reports the total amount of
1827 * transferred data and presents it in a contiguous chunk.
1829 if (urb->actual_length > 0) {
1830 struct libusb_transfer *transfer =
1831 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1832 unsigned char *target = transfer->buffer + itransfer->transferred;
1833 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
1834 if (urb->buffer != target) {
1835 usbi_dbg("moving surplus data from offset %d to offset %d",
1836 (unsigned char *) urb->buffer - transfer->buffer,
1837 target - transfer->buffer);
1838 memmove(target, urb->buffer, urb->actual_length);
1840 itransfer->transferred += urb->actual_length;
1843 if (tpriv->num_retired == num_urbs) {
1844 usbi_dbg("abnormal reap: last URB handled, reporting");
1845 if (tpriv->reap_action == CANCELLED) {
1846 free(tpriv->urbs);
1847 tpriv->urbs = NULL;
1848 pthread_mutex_unlock(&itransfer->lock);
1849 r = usbi_handle_transfer_cancellation(itransfer);
1850 goto out_unlock;
1852 if (tpriv->reap_action != COMPLETED_EARLY)
1853 status = LIBUSB_TRANSFER_ERROR;
1854 goto completed;
1856 goto out_unlock;
1859 if (urb->status == 0 || urb->status == -EREMOTEIO ||
1860 (urb->status == -EOVERFLOW && urb->actual_length > 0))
1861 itransfer->transferred += urb->actual_length;
1864 switch (urb->status) {
1865 case 0:
1866 break;
1867 case -EREMOTEIO: /* short transfer */
1868 break;
1869 case -EPIPE:
1870 usbi_dbg("detected endpoint stall");
1871 status = LIBUSB_TRANSFER_STALL;
1872 goto completed;
1873 case -EOVERFLOW:
1874 /* overflow can only ever occur in the last urb */
1875 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
1876 status = LIBUSB_TRANSFER_OVERFLOW;
1877 goto completed;
1878 case -ETIME:
1879 case -EPROTO:
1880 case -EILSEQ:
1881 usbi_dbg("low level error %d", urb->status);
1882 status = LIBUSB_TRANSFER_ERROR;
1883 goto completed;
1884 default:
1885 usbi_warn(ITRANSFER_CTX(itransfer),
1886 "unrecognised urb status %d", urb->status);
1887 status = LIBUSB_TRANSFER_ERROR;
1888 goto completed;
1891 /* if we're the last urb or we got less data than requested then we're
1892 * done */
1893 if (urb_idx == num_urbs - 1) {
1894 usbi_dbg("last URB in transfer --> complete!");
1895 } else if (urb->actual_length < urb->buffer_length) {
1896 struct libusb_transfer *transfer =
1897 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1898 struct linux_device_handle_priv *dpriv =
1899 __device_handle_priv(transfer->dev_handle);
1900 int i;
1902 usbi_dbg("short transfer %d/%d --> complete!", urb->actual_length,
1903 urb->buffer_length);
1905 /* we have to cancel the remaining urbs and wait for their completion
1906 * before reporting results */
1907 tpriv->reap_action = COMPLETED_EARLY;
1908 for (i = urb_idx + 1; i < tpriv->num_urbs; i++) {
1909 /* remaining URBs with continuation flag are automatically
1910 * cancelled by the kernel */
1911 if (tpriv->urbs[i].flags & USBFS_URB_BULK_CONTINUATION)
1912 continue;
1913 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1914 if (tmp && errno != EINVAL)
1915 usbi_warn(TRANSFER_CTX(transfer),
1916 "unrecognised discard errno %d", errno);
1918 goto out_unlock;
1919 } else {
1920 goto out_unlock;
1923 completed:
1924 free(tpriv->urbs);
1925 tpriv->urbs = NULL;
1926 pthread_mutex_unlock(&itransfer->lock);
1927 return usbi_handle_transfer_completion(itransfer, status);
1928 out_unlock:
1929 pthread_mutex_unlock(&itransfer->lock);
1930 return r;
1933 static int handle_iso_completion(struct usbi_transfer *itransfer,
1934 struct usbfs_urb *urb)
1936 struct libusb_transfer *transfer =
1937 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1938 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1939 int num_urbs = tpriv->num_urbs;
1940 int urb_idx = 0;
1941 int i;
1943 pthread_mutex_lock(&itransfer->lock);
1944 for (i = 0; i < num_urbs; i++) {
1945 if (urb == tpriv->iso_urbs[i]) {
1946 urb_idx = i + 1;
1947 break;
1950 if (urb_idx == 0) {
1951 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
1952 pthread_mutex_unlock(&itransfer->lock);
1953 return LIBUSB_ERROR_NOT_FOUND;
1956 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
1957 urb_idx, num_urbs);
1959 if (urb->status == 0) {
1960 /* copy isochronous results back in */
1962 for (i = 0; i < urb->number_of_packets; i++) {
1963 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
1964 struct libusb_iso_packet_descriptor *lib_desc =
1965 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
1966 lib_desc->status = urb_desc->status;
1967 lib_desc->actual_length = urb_desc->actual_length;
1971 tpriv->num_retired++;
1973 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
1974 usbi_dbg("CANCEL: urb status %d", urb->status);
1976 if (tpriv->num_retired == num_urbs) {
1977 usbi_dbg("CANCEL: last URB handled, reporting");
1978 free_iso_urbs(tpriv);
1979 if (tpriv->reap_action == CANCELLED) {
1980 pthread_mutex_unlock(&itransfer->lock);
1981 return usbi_handle_transfer_cancellation(itransfer);
1982 } else {
1983 pthread_mutex_unlock(&itransfer->lock);
1984 return usbi_handle_transfer_completion(itransfer,
1985 LIBUSB_TRANSFER_ERROR);
1988 goto out;
1991 switch (urb->status) {
1992 case 0:
1993 break;
1994 case -ETIME:
1995 case -EPROTO:
1996 case -EILSEQ:
1997 usbi_dbg("low-level USB error %d", urb->status);
1998 break;
1999 default:
2000 usbi_warn(TRANSFER_CTX(transfer),
2001 "unrecognised urb status %d", urb->status);
2002 break;
2005 /* if we're the last urb or we got less data than requested then we're
2006 * done */
2007 if (urb_idx == num_urbs) {
2008 usbi_dbg("last URB in transfer --> complete!");
2009 free_iso_urbs(tpriv);
2010 pthread_mutex_unlock(&itransfer->lock);
2011 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED);
2014 out:
2015 pthread_mutex_unlock(&itransfer->lock);
2016 return 0;
2019 static int handle_control_completion(struct usbi_transfer *itransfer,
2020 struct usbfs_urb *urb)
2022 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2023 int status;
2025 pthread_mutex_lock(&itransfer->lock);
2026 usbi_dbg("handling completion status %d", urb->status);
2028 if (urb->status == 0)
2029 itransfer->transferred += urb->actual_length;
2031 if (tpriv->reap_action == CANCELLED) {
2032 if (urb->status != 0 && urb->status != -ENOENT)
2033 usbi_warn(ITRANSFER_CTX(itransfer),
2034 "cancel: unrecognised urb status %d", urb->status);
2035 free(tpriv->urbs);
2036 tpriv->urbs = NULL;
2037 pthread_mutex_unlock(&itransfer->lock);
2038 return usbi_handle_transfer_cancellation(itransfer);
2041 switch (urb->status) {
2042 case 0:
2043 itransfer->transferred = urb->actual_length;
2044 status = LIBUSB_TRANSFER_COMPLETED;
2045 break;
2046 case -EPIPE:
2047 usbi_dbg("unsupported control request");
2048 status = LIBUSB_TRANSFER_STALL;
2049 break;
2050 case -ETIME:
2051 case -EPROTO:
2052 case -EILSEQ:
2053 usbi_dbg("low-level bus error occurred");
2054 status = LIBUSB_TRANSFER_ERROR;
2055 break;
2056 default:
2057 usbi_warn(ITRANSFER_CTX(itransfer),
2058 "unrecognised urb status %d", urb->status);
2059 status = LIBUSB_TRANSFER_ERROR;
2060 break;
2063 free(tpriv->urbs);
2064 tpriv->urbs = NULL;
2065 pthread_mutex_unlock(&itransfer->lock);
2066 return usbi_handle_transfer_completion(itransfer, status);
2069 static int reap_for_handle(struct libusb_device_handle *handle)
2071 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
2072 int r;
2073 struct usbfs_urb *urb;
2074 struct usbi_transfer *itransfer;
2075 struct libusb_transfer *transfer;
2077 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2078 if (r == -1 && errno == EAGAIN)
2079 return 1;
2080 if (r < 0) {
2081 if (errno == ENODEV)
2082 return LIBUSB_ERROR_NO_DEVICE;
2084 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2085 r, errno);
2086 return LIBUSB_ERROR_IO;
2089 itransfer = urb->usercontext;
2090 transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2092 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2093 urb->actual_length);
2095 switch (transfer->type) {
2096 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2097 return handle_iso_completion(itransfer, urb);
2098 case LIBUSB_TRANSFER_TYPE_BULK:
2099 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2100 return handle_bulk_completion(itransfer, urb);
2101 case LIBUSB_TRANSFER_TYPE_CONTROL:
2102 return handle_control_completion(itransfer, urb);
2103 default:
2104 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2105 transfer->type);
2106 return LIBUSB_ERROR_OTHER;
2110 static int op_handle_events(struct libusb_context *ctx,
2111 struct pollfd *fds, nfds_t nfds, int num_ready)
2113 int r;
2114 int i = 0;
2116 pthread_mutex_lock(&ctx->open_devs_lock);
2117 for (i = 0; i < nfds && num_ready > 0; i++) {
2118 struct pollfd *pollfd = &fds[i];
2119 struct libusb_device_handle *handle;
2120 struct linux_device_handle_priv *hpriv = NULL;
2122 if (!pollfd->revents)
2123 continue;
2125 num_ready--;
2126 list_for_each_entry(handle, &ctx->open_devs, list) {
2127 hpriv = __device_handle_priv(handle);
2128 if (hpriv->fd == pollfd->fd)
2129 break;
2132 if (pollfd->revents & POLLERR) {
2133 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2134 usbi_handle_disconnect(handle);
2135 continue;
2138 r = reap_for_handle(handle);
2139 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2140 continue;
2141 else if (r < 0)
2142 goto out;
2145 r = 0;
2146 out:
2147 pthread_mutex_unlock(&ctx->open_devs_lock);
2148 return r;
2151 static int op_clock_gettime(int clk_id, struct timespec *tp)
2153 switch (clk_id) {
2154 case USBI_CLOCK_MONOTONIC:
2155 return clock_gettime(monotonic_clkid, tp);
2156 case USBI_CLOCK_REALTIME:
2157 return clock_gettime(CLOCK_REALTIME, tp);
2158 default:
2159 return LIBUSB_ERROR_INVALID_PARAM;
2163 #ifdef USBI_TIMERFD_AVAILABLE
2164 static clockid_t op_get_timerfd_clockid(void)
2166 return monotonic_clkid;
2169 #endif
2171 const struct usbi_os_backend linux_usbfs_backend = {
2172 .name = "Linux usbfs",
2173 .init = op_init,
2174 .exit = NULL,
2175 .get_device_list = op_get_device_list,
2176 .get_device_descriptor = op_get_device_descriptor,
2177 .get_active_config_descriptor = op_get_active_config_descriptor,
2178 .get_config_descriptor = op_get_config_descriptor,
2180 .open = op_open,
2181 .close = op_close,
2182 .get_configuration = op_get_configuration,
2183 .set_configuration = op_set_configuration,
2184 .claim_interface = op_claim_interface,
2185 .release_interface = op_release_interface,
2187 .set_interface_altsetting = op_set_interface,
2188 .clear_halt = op_clear_halt,
2189 .reset_device = op_reset_device,
2191 .kernel_driver_active = op_kernel_driver_active,
2192 .detach_kernel_driver = op_detach_kernel_driver,
2193 .attach_kernel_driver = op_attach_kernel_driver,
2195 .destroy_device = op_destroy_device,
2197 .submit_transfer = op_submit_transfer,
2198 .cancel_transfer = op_cancel_transfer,
2199 .clear_transfer_priv = op_clear_transfer_priv,
2201 .handle_events = op_handle_events,
2203 .clock_gettime = op_clock_gettime,
2205 #ifdef USBI_TIMERFD_AVAILABLE
2206 .get_timerfd_clockid = op_get_timerfd_clockid,
2207 #endif
2209 .device_priv_size = sizeof(struct linux_device_priv),
2210 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2211 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2212 .add_iso_packet_size = 0,