Core: Add HID and kernel detach capability detection for all backends
[libusbx.git] / libusb / os / linux_usbfs.c
blob95e533910a3d4aa3f2ab2267034d59b148c3b70b
1 /*
2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 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 <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/ioctl.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <sys/utsname.h>
34 #include <unistd.h>
36 #include "libusb.h"
37 #include "libusbi.h"
38 #include "linux_usbfs.h"
40 /* sysfs vs usbfs:
41 * opening a usbfs node causes the device to be resumed, so we attempt to
42 * avoid this during enumeration.
44 * sysfs allows us to read the kernel's in-memory copies of device descriptors
45 * and so forth, avoiding the need to open the device:
46 * - The binary "descriptors" file was added in 2.6.23.
47 * - The "busnum" file was added in 2.6.22
48 * - The "devnum" file has been present since pre-2.6.18
49 * - the "bConfigurationValue" file has been present since pre-2.6.18
51 * If we have bConfigurationValue, busnum, and devnum, then we can determine
52 * the active configuration without having to open the usbfs node in RDWR mode.
53 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
54 * The busnum file is important as that is the only way we can relate sysfs
55 * devices to usbfs nodes.
57 * If we also have descriptors, we can obtain the device descriptor and active
58 * configuration without touching usbfs at all.
60 * The descriptors file originally only contained the active configuration
61 * descriptor alongside the device descriptor, but all configurations are
62 * included as of Linux 2.6.26.
65 /* endianness for multi-byte fields:
67 * Descriptors exposed by usbfs have the multi-byte fields in the device
68 * descriptor as host endian. Multi-byte fields in the other descriptors are
69 * bus-endian. The kernel documentation says otherwise, but it is wrong.
72 static const char *usbfs_path = NULL;
74 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
75 static int usbdev_names = 0;
77 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
78 * allows us to mark URBs as being part of a specific logical transfer when
79 * we submit them to the kernel. then, on any error except a cancellation, all
80 * URBs within that transfer will be cancelled and no more URBs will be
81 * accepted for the transfer, meaning that no more data can creep in.
83 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
84 * (in either direction) except the first.
85 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
86 * last; it means that the kernel should treat a short reply as an error.
87 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
88 * transfers can't be short unless there's already some sort of error), and
89 * setting this flag is disallowed (a kernel with USB debugging enabled will
90 * reject such URBs).
92 static int supports_flag_bulk_continuation = -1;
94 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
95 * allows us to mark URBs that should be followed by a zero length data
96 * packet, which can be required by device- or class-specific protocols.
98 static int supports_flag_zero_packet = -1;
100 /* clock ID for monotonic clock, as not all clock sources are available on all
101 * systems. appropriate choice made at initialization time. */
102 static clockid_t monotonic_clkid = -1;
104 /* do we have a busnum to relate devices? this also implies that we can read
105 * the active configuration through bConfigurationValue */
106 static int sysfs_can_relate_devices = 0;
108 /* do we have a descriptors file? */
109 static int sysfs_has_descriptors = 0;
111 struct linux_device_priv {
112 char *sysfs_dir;
113 unsigned char *dev_descriptor;
114 unsigned char *config_descriptor;
117 struct linux_device_handle_priv {
118 int fd;
119 uint32_t caps;
122 enum reap_action {
123 NORMAL = 0,
124 /* submission failed after the first URB, so await cancellation/completion
125 * of all the others */
126 SUBMIT_FAILED,
128 /* cancelled by user or timeout */
129 CANCELLED,
131 /* completed multi-URB transfer in non-final URB */
132 COMPLETED_EARLY,
134 /* one or more urbs encountered a low-level error */
135 ERROR,
138 struct linux_transfer_priv {
139 union {
140 struct usbfs_urb *urbs;
141 struct usbfs_urb **iso_urbs;
144 enum reap_action reap_action;
145 int num_urbs;
146 int num_retired;
147 enum libusb_transfer_status reap_status;
149 /* next iso packet in user-supplied transfer to be populated */
150 int iso_packet_offset;
153 static void _get_usbfs_path(struct libusb_device *dev, char *path)
155 if (usbdev_names)
156 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
157 usbfs_path, dev->bus_number, dev->device_address);
158 else
159 snprintf(path, PATH_MAX, "%s/%03d/%03d",
160 usbfs_path, dev->bus_number, dev->device_address);
163 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
165 return (struct linux_device_priv *) dev->os_priv;
168 static struct linux_device_handle_priv *_device_handle_priv(
169 struct libusb_device_handle *handle)
171 return (struct linux_device_handle_priv *) handle->os_priv;
174 /* check dirent for a /dev/usbdev%d.%d name
175 * optionally return bus/device on success */
176 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
178 int busnum, devnum;
180 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
181 return 0;
183 usbi_dbg("found: %s", entry->d_name);
184 if (bus_p != NULL)
185 *bus_p = busnum;
186 if (dev_p != NULL)
187 *dev_p = devnum;
188 return 1;
191 static int check_usb_vfs(const char *dirname)
193 DIR *dir;
194 struct dirent *entry;
195 int found = 0;
197 dir = opendir(dirname);
198 if (!dir)
199 return 0;
201 while ((entry = readdir(dir)) != NULL) {
202 if (entry->d_name[0] == '.')
203 continue;
205 /* We assume if we find any files that it must be the right place */
206 found = 1;
207 break;
210 closedir(dir);
211 return found;
214 static const char *find_usbfs_path(void)
216 const char *path = "/dev/bus/usb";
217 const char *ret = NULL;
219 if (check_usb_vfs(path)) {
220 ret = path;
221 } else {
222 path = "/proc/bus/usb";
223 if (check_usb_vfs(path))
224 ret = path;
227 /* look for /dev/usbdev*.* if the normal places fail */
228 if (ret == NULL) {
229 struct dirent *entry;
230 DIR *dir;
232 path = "/dev";
233 dir = opendir(path);
234 if (dir != NULL) {
235 while ((entry = readdir(dir)) != NULL) {
236 if (_is_usbdev_entry(entry, NULL, NULL)) {
237 /* found one; that's enough */
238 ret = path;
239 usbdev_names = 1;
240 break;
243 closedir(dir);
247 if (ret != NULL)
248 usbi_dbg("found usbfs at %s", ret);
250 return ret;
253 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
254 * seem to lack it). fall back to REALTIME if we have to. */
255 static clockid_t find_monotonic_clock(void)
257 #ifdef CLOCK_MONOTONIC
258 struct timespec ts;
259 int r;
261 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
262 * because it's not available through timerfd */
263 r = clock_gettime(CLOCK_MONOTONIC, &ts);
264 if (r == 0)
265 return CLOCK_MONOTONIC;
266 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
267 #endif
269 return CLOCK_REALTIME;
272 static int kernel_version_ge(int major, int minor, int sublevel)
274 struct utsname uts;
275 int atoms, kmajor, kminor, ksublevel;
277 if (uname(&uts) < 0)
278 return -1;
279 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
280 if (atoms < 1)
281 return -1;
283 if (kmajor > major)
284 return 1;
285 if (kmajor < major)
286 return 0;
288 /* kmajor == major */
289 if (atoms < 2)
290 return 0 == minor && 0 == sublevel;
291 if (kminor > minor)
292 return 1;
293 if (kminor < minor)
294 return 0;
296 /* kminor == minor */
297 if (atoms < 3)
298 return 0 == sublevel;
300 return ksublevel >= sublevel;
303 /* Return 1 if filename exists inside dirname in sysfs.
304 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
305 static int sysfs_has_file(const char *dirname, const char *filename)
307 struct stat statbuf;
308 char path[PATH_MAX];
309 int r;
311 snprintf(path, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, dirname, filename);
312 r = stat(path, &statbuf);
313 if (r == 0 && S_ISREG(statbuf.st_mode))
314 return 1;
316 return 0;
319 static int op_init(struct libusb_context *ctx)
321 struct stat statbuf;
322 int r;
324 usbfs_path = find_usbfs_path();
325 if (!usbfs_path) {
326 usbi_err(ctx, "could not find usbfs");
327 return LIBUSB_ERROR_OTHER;
330 if (monotonic_clkid == -1)
331 monotonic_clkid = find_monotonic_clock();
333 if (supports_flag_bulk_continuation == -1) {
334 /* bulk continuation URB flag available from Linux 2.6.32 */
335 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
336 if (supports_flag_bulk_continuation == -1) {
337 usbi_err(ctx, "error checking for bulk continuation support");
338 return LIBUSB_ERROR_OTHER;
342 if (supports_flag_bulk_continuation)
343 usbi_dbg("bulk continuation flag supported");
345 if (-1 == supports_flag_zero_packet) {
346 /* zero length packet URB flag fixed since Linux 2.6.31 */
347 supports_flag_zero_packet = kernel_version_ge(2,6,31);
348 if (-1 == supports_flag_zero_packet) {
349 usbi_err(ctx, "error checking for zero length packet support");
350 return LIBUSB_ERROR_OTHER;
354 if (supports_flag_zero_packet)
355 usbi_dbg("zero length packet flag supported");
357 r = stat(SYSFS_DEVICE_PATH, &statbuf);
358 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
359 DIR *devices = opendir(SYSFS_DEVICE_PATH);
360 struct dirent *entry;
362 usbi_dbg("found usb devices in sysfs");
364 if (!devices) {
365 usbi_err(ctx, "opendir devices failed errno=%d", errno);
366 return LIBUSB_ERROR_IO;
369 /* Make sure sysfs supports all the required files. If it
370 * does not, then usbfs will be used instead. Determine
371 * this by looping through the directories in
372 * SYSFS_DEVICE_PATH. With the assumption that there will
373 * always be subdirectories of the name usbN (usb1, usb2,
374 * etc) representing the root hubs, check the usbN
375 * subdirectories to see if they have all the needed files.
376 * This algorithm uses the usbN subdirectories (root hubs)
377 * because a device disconnection will cause a race
378 * condition regarding which files are available, sometimes
379 * causing an incorrect result. The root hubs are used
380 * because it is assumed that they will always be present.
381 * See the "sysfs vs usbfs" comment at the top of this file
382 * for more details. */
383 while ((entry = readdir(devices))) {
384 int has_busnum=0, has_devnum=0, has_descriptors=0;
385 int has_configuration_value=0;
387 /* Only check the usbN directories. */
388 if (strncmp(entry->d_name, "usb", 3) != 0)
389 continue;
391 /* Check for the files libusbx needs from sysfs. */
392 has_busnum = sysfs_has_file(entry->d_name, "busnum");
393 has_devnum = sysfs_has_file(entry->d_name, "devnum");
394 has_descriptors = sysfs_has_file(entry->d_name, "descriptors");
395 has_configuration_value = sysfs_has_file(entry->d_name, "bConfigurationValue");
397 if (has_busnum && has_devnum && has_configuration_value)
398 sysfs_can_relate_devices = 1;
399 if (has_descriptors)
400 sysfs_has_descriptors = 1;
402 /* Only need to check until we've found ONE device which
403 has all the attributes. */
404 if (sysfs_has_descriptors && sysfs_can_relate_devices)
405 break;
407 closedir(devices);
409 /* Only use sysfs descriptors if the rest of
410 sysfs will work for libusb. */
411 if (!sysfs_can_relate_devices)
412 sysfs_has_descriptors = 0;
413 } else {
414 usbi_dbg("sysfs usb info not available");
415 sysfs_has_descriptors = 0;
416 sysfs_can_relate_devices = 0;
419 return 0;
422 static int usbfs_get_device_descriptor(struct libusb_device *dev,
423 unsigned char *buffer)
425 struct linux_device_priv *priv = _device_priv(dev);
427 /* return cached copy */
428 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
429 return 0;
432 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
434 struct linux_device_priv *priv = _device_priv(dev);
435 char filename[PATH_MAX];
436 int fd;
438 snprintf(filename, PATH_MAX, "%s/%s/%s",
439 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
440 fd = open(filename, O_RDONLY);
441 if (fd < 0) {
442 usbi_err(DEVICE_CTX(dev),
443 "open %s failed ret=%d errno=%d", filename, fd, errno);
444 return LIBUSB_ERROR_IO;
447 return fd;
450 /* Note only suitable for attributes which always read >= 0, < 0 is error */
451 static int __read_sysfs_attr(struct libusb_context *ctx,
452 const char *devname, const char *attr)
454 char filename[PATH_MAX];
455 FILE *f;
456 int r, value;
458 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
459 devname, attr);
460 f = fopen(filename, "r");
461 if (f == NULL) {
462 if (errno == ENOENT) {
463 /* File doesn't exist. Assume the device has been
464 disconnected (see trac ticket #70). */
465 return LIBUSB_ERROR_NO_DEVICE;
467 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
468 return LIBUSB_ERROR_IO;
471 r = fscanf(f, "%d", &value);
472 fclose(f);
473 if (r != 1) {
474 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
475 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
477 if (value < 0) {
478 usbi_err(ctx, "%s contains a negative value", filename);
479 return LIBUSB_ERROR_IO;
482 return value;
485 static int sysfs_get_device_descriptor(struct libusb_device *dev,
486 unsigned char *buffer)
488 int fd;
489 ssize_t r;
491 /* sysfs provides access to an in-memory copy of the device descriptor,
492 * so we use that rather than keeping our own copy */
494 fd = _open_sysfs_attr(dev, "descriptors");
495 if (fd < 0)
496 return fd;
498 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
499 close(fd);
500 if (r < 0) {
501 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
502 return LIBUSB_ERROR_IO;
503 } else if (r < DEVICE_DESC_LENGTH) {
504 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
505 return LIBUSB_ERROR_IO;
508 return 0;
511 static int op_get_device_descriptor(struct libusb_device *dev,
512 unsigned char *buffer, int *host_endian)
514 if (sysfs_has_descriptors) {
515 return sysfs_get_device_descriptor(dev, buffer);
516 } else {
517 *host_endian = 1;
518 return usbfs_get_device_descriptor(dev, buffer);
522 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
523 unsigned char *buffer, size_t len)
525 struct linux_device_priv *priv = _device_priv(dev);
526 if (!priv->config_descriptor)
527 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
529 /* retrieve cached copy */
530 memcpy(buffer, priv->config_descriptor, len);
531 return 0;
534 /* read the bConfigurationValue for a device */
535 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
537 char *endptr;
538 char tmp[4] = {0, 0, 0, 0};
539 long num;
540 int fd;
541 ssize_t r;
543 fd = _open_sysfs_attr(dev, "bConfigurationValue");
544 if (fd < 0)
545 return fd;
547 r = read(fd, tmp, sizeof(tmp));
548 close(fd);
549 if (r < 0) {
550 usbi_err(DEVICE_CTX(dev),
551 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
552 return LIBUSB_ERROR_IO;
553 } else if (r == 0) {
554 usbi_dbg("device unconfigured");
555 *config = -1;
556 return 0;
559 if (tmp[sizeof(tmp) - 1] != 0) {
560 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
561 return LIBUSB_ERROR_IO;
562 } else if (tmp[0] == 0) {
563 usbi_err(DEVICE_CTX(dev), "no configuration value?");
564 return LIBUSB_ERROR_IO;
567 num = strtol(tmp, &endptr, 10);
568 if (endptr == tmp) {
569 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
570 return LIBUSB_ERROR_IO;
573 *config = (int) num;
574 return 0;
577 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
578 * seeks to the next one. */
579 static int seek_to_next_config(struct libusb_context *ctx, int fd,
580 int host_endian)
582 struct libusb_config_descriptor config;
583 unsigned char tmp[6];
584 off_t off;
585 ssize_t r;
587 /* read first 6 bytes of descriptor */
588 r = read(fd, tmp, sizeof(tmp));
589 if (r < 0) {
590 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
591 return LIBUSB_ERROR_IO;
592 } else if (r < sizeof(tmp)) {
593 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
594 return LIBUSB_ERROR_IO;
597 /* seek forward to end of config */
598 usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
599 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
600 if (off < 0) {
601 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
602 return LIBUSB_ERROR_IO;
605 return 0;
608 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
609 unsigned char *buffer, size_t len)
611 int fd;
612 ssize_t r;
613 off_t off;
614 int to_copy;
615 int config;
616 unsigned char tmp[6];
618 r = sysfs_get_active_config(dev, &config);
619 if (r < 0)
620 return r;
621 if (config == -1)
622 return LIBUSB_ERROR_NOT_FOUND;
624 usbi_dbg("active configuration %d", config);
626 /* sysfs provides access to an in-memory copy of the device descriptor,
627 * so we use that rather than keeping our own copy */
629 fd = _open_sysfs_attr(dev, "descriptors");
630 if (fd < 0)
631 return fd;
633 /* device might have been unconfigured since we read bConfigurationValue,
634 * so first check that there is any config descriptor data at all... */
635 off = lseek(fd, 0, SEEK_END);
636 if (off < 1) {
637 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
638 off, errno);
639 close(fd);
640 return LIBUSB_ERROR_IO;
641 } else if (off == DEVICE_DESC_LENGTH) {
642 close(fd);
643 return LIBUSB_ERROR_NOT_FOUND;
646 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
647 if (off < 0) {
648 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
649 close(fd);
650 return LIBUSB_ERROR_IO;
653 /* unbounded loop: we expect the descriptor to be present under all
654 * circumstances */
655 while (1) {
656 r = read(fd, tmp, sizeof(tmp));
657 if (r < 0) {
658 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
659 fd, errno);
660 return LIBUSB_ERROR_IO;
661 } else if (r < sizeof(tmp)) {
662 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
663 return LIBUSB_ERROR_IO;
666 /* check bConfigurationValue */
667 if (tmp[5] == config)
668 break;
670 /* try the next descriptor */
671 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
672 if (off < 0)
673 return LIBUSB_ERROR_IO;
675 r = seek_to_next_config(DEVICE_CTX(dev), fd, 0);
676 if (r < 0)
677 return r;
680 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
681 memcpy(buffer, tmp, to_copy);
682 if (len > sizeof(tmp)) {
683 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
684 if (r < 0) {
685 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
686 fd, errno);
687 r = LIBUSB_ERROR_IO;
688 } else if (r == 0) {
689 usbi_dbg("device is unconfigured");
690 r = LIBUSB_ERROR_NOT_FOUND;
691 } else if (r < len - sizeof(tmp)) {
692 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
693 r = 0;
695 } else {
696 r = 0;
699 close(fd);
700 return r;
703 static int op_get_active_config_descriptor(struct libusb_device *dev,
704 unsigned char *buffer, size_t len, int *host_endian)
706 if (sysfs_has_descriptors) {
707 return sysfs_get_active_config_descriptor(dev, buffer, len);
708 } else {
709 return usbfs_get_active_config_descriptor(dev, buffer, len);
713 /* takes a usbfs fd, attempts to find the requested config and copy a certain
714 * amount of it into an output buffer. */
715 static int get_config_descriptor(struct libusb_context *ctx, int fd,
716 uint8_t config_index, unsigned char *buffer, size_t len)
718 off_t off;
719 ssize_t r;
721 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
722 if (off < 0) {
723 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
724 return LIBUSB_ERROR_IO;
727 /* might need to skip some configuration descriptors to reach the
728 * requested configuration */
729 while (config_index > 0) {
730 r = seek_to_next_config(ctx, fd, 1);
731 if (r < 0)
732 return r;
733 config_index--;
736 /* read the rest of the descriptor */
737 r = read(fd, buffer, len);
738 if (r < 0) {
739 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
740 return LIBUSB_ERROR_IO;
741 } else if (r < len) {
742 usbi_err(ctx, "short output read %d/%d", r, len);
745 return 0;
748 static int op_get_config_descriptor(struct libusb_device *dev,
749 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
751 char filename[PATH_MAX];
752 int fd;
753 int r;
755 /* always read from usbfs: sysfs only has the active descriptor
756 * this will involve waking the device up, but oh well! */
758 /* FIXME: the above is no longer true, new kernels have all descriptors
759 * in the descriptors file. but its kinda hard to detect if the kernel
760 * is sufficiently new. */
762 _get_usbfs_path(dev, filename);
763 fd = open(filename, O_RDONLY);
764 if (fd < 0) {
765 usbi_err(DEVICE_CTX(dev),
766 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
767 return LIBUSB_ERROR_IO;
770 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
771 close(fd);
772 return r;
775 /* cache the active config descriptor in memory. a value of -1 means that
776 * we aren't sure which one is active, so just assume the first one.
777 * only for usbfs. */
778 static int cache_active_config(struct libusb_device *dev, int fd,
779 int active_config)
781 struct linux_device_priv *priv = _device_priv(dev);
782 struct libusb_config_descriptor config;
783 unsigned char tmp[8];
784 unsigned char *buf;
785 int idx;
786 int r;
788 if (active_config == -1) {
789 idx = 0;
790 } else {
791 r = usbi_get_config_index_by_value(dev, active_config, &idx);
792 if (r < 0)
793 return r;
794 if (idx == -1)
795 return LIBUSB_ERROR_NOT_FOUND;
798 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
799 if (r < 0) {
800 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
801 return r;
804 usbi_parse_descriptor(tmp, "bbw", &config, 0);
805 buf = malloc(config.wTotalLength);
806 if (!buf)
807 return LIBUSB_ERROR_NO_MEM;
809 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
810 config.wTotalLength);
811 if (r < 0) {
812 free(buf);
813 return r;
816 if (priv->config_descriptor)
817 free(priv->config_descriptor);
818 priv->config_descriptor = buf;
819 return 0;
822 /* send a control message to retrieve active configuration */
823 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
825 unsigned char active_config = 0;
826 int r;
828 struct usbfs_ctrltransfer ctrl = {
829 .bmRequestType = LIBUSB_ENDPOINT_IN,
830 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
831 .wValue = 0,
832 .wIndex = 0,
833 .wLength = 1,
834 .timeout = 1000,
835 .data = &active_config
838 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
839 if (r < 0) {
840 if (errno == ENODEV)
841 return LIBUSB_ERROR_NO_DEVICE;
843 /* we hit this error path frequently with buggy devices :( */
844 usbi_warn(DEVICE_CTX(dev),
845 "get_configuration failed ret=%d errno=%d", r, errno);
846 return LIBUSB_ERROR_IO;
849 return active_config;
852 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
853 uint8_t devaddr, const char *sysfs_dir)
855 struct linux_device_priv *priv = _device_priv(dev);
856 unsigned char *dev_buf;
857 char path[PATH_MAX];
858 int fd, speed;
859 int active_config = 0;
860 int device_configured = 1;
861 ssize_t r;
863 dev->bus_number = busnum;
864 dev->device_address = devaddr;
866 if (sysfs_dir) {
867 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
868 if (!priv->sysfs_dir)
869 return LIBUSB_ERROR_NO_MEM;
870 strcpy(priv->sysfs_dir, sysfs_dir);
872 /* Note speed can contain 1.5, in this case __read_sysfs_attr
873 will stop parsing at the '.' and return 1 */
874 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
875 if (speed >= 0) {
876 switch (speed) {
877 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
878 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
879 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
880 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
881 default:
882 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
887 if (sysfs_has_descriptors)
888 return 0;
890 /* cache device descriptor in memory so that we can retrieve it later
891 * without waking the device up (op_get_device_descriptor) */
893 priv->dev_descriptor = NULL;
894 priv->config_descriptor = NULL;
896 if (sysfs_can_relate_devices) {
897 int tmp = sysfs_get_active_config(dev, &active_config);
898 if (tmp < 0)
899 return tmp;
900 if (active_config == -1)
901 device_configured = 0;
904 _get_usbfs_path(dev, path);
905 fd = open(path, O_RDWR);
906 if (fd < 0 && errno == EACCES) {
907 fd = open(path, O_RDONLY);
908 /* if we only have read-only access to the device, we cannot
909 * send a control message to determine the active config. just
910 * assume the first one is active. */
911 active_config = -1;
914 if (fd < 0) {
915 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
916 return LIBUSB_ERROR_IO;
919 if (!sysfs_can_relate_devices) {
920 if (active_config == -1) {
921 /* if we only have read-only access to the device, we cannot
922 * send a control message to determine the active config. just
923 * assume the first one is active. */
924 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
925 "determine active configuration descriptor", path);
926 } else {
927 active_config = usbfs_get_active_config(dev, fd);
928 if (active_config == LIBUSB_ERROR_IO) {
929 /* buggy devices sometimes fail to report their active config.
930 * assume unconfigured and continue the probing */
931 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
932 "configuration, assumung unconfigured");
933 device_configured = 0;
934 } else if (active_config < 0) {
935 close(fd);
936 return active_config;
937 } else if (active_config == 0) {
938 /* some buggy devices have a configuration 0, but we're
939 * reaching into the corner of a corner case here, so let's
940 * not support buggy devices in these circumstances.
941 * stick to the specs: a configuration value of 0 means
942 * unconfigured. */
943 usbi_dbg("active cfg 0? assuming unconfigured device");
944 device_configured = 0;
949 dev_buf = malloc(DEVICE_DESC_LENGTH);
950 if (!dev_buf) {
951 close(fd);
952 return LIBUSB_ERROR_NO_MEM;
955 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
956 if (r < 0) {
957 usbi_err(DEVICE_CTX(dev),
958 "read descriptor failed ret=%d errno=%d", fd, errno);
959 free(dev_buf);
960 close(fd);
961 return LIBUSB_ERROR_IO;
962 } else if (r < DEVICE_DESC_LENGTH) {
963 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
964 free(dev_buf);
965 close(fd);
966 return LIBUSB_ERROR_IO;
969 /* bit of a hack: set num_configurations now because cache_active_config()
970 * calls usbi_get_config_index_by_value() which uses it */
971 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
973 if (device_configured) {
974 r = cache_active_config(dev, fd, active_config);
975 if (r < 0) {
976 close(fd);
977 free(dev_buf);
978 return r;
982 close(fd);
983 priv->dev_descriptor = dev_buf;
984 return 0;
987 static int enumerate_device(struct libusb_context *ctx,
988 struct discovered_devs **_discdevs, uint8_t busnum, uint8_t devaddr,
989 const char *sysfs_dir)
991 struct discovered_devs *discdevs;
992 unsigned long session_id;
993 int need_unref = 0;
994 struct libusb_device *dev;
995 int r = 0;
997 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
998 * will be reused. instead we should add a simple sysfs attribute with
999 * a session ID. */
1000 session_id = busnum << 8 | devaddr;
1001 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1002 session_id);
1004 dev = usbi_get_device_by_session_id(ctx, session_id);
1005 if (dev) {
1006 usbi_dbg("using existing device for %d/%d (session %ld)",
1007 busnum, devaddr, session_id);
1008 } else {
1009 usbi_dbg("allocating new device for %d/%d (session %ld)",
1010 busnum, devaddr, session_id);
1011 dev = usbi_alloc_device(ctx, session_id);
1012 if (!dev)
1013 return LIBUSB_ERROR_NO_MEM;
1014 need_unref = 1;
1015 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1016 if (r < 0)
1017 goto out;
1018 r = usbi_sanitize_device(dev);
1019 if (r < 0)
1020 goto out;
1023 discdevs = discovered_devs_append(*_discdevs, dev);
1024 if (!discdevs)
1025 r = LIBUSB_ERROR_NO_MEM;
1026 else
1027 *_discdevs = discdevs;
1029 out:
1030 if (need_unref)
1031 libusb_unref_device(dev);
1032 return r;
1035 /* open a bus directory and adds all discovered devices to discdevs. on
1036 * failure (non-zero return) the pre-existing discdevs should be destroyed
1037 * (and devices freed). on success, the new discdevs pointer should be used
1038 * as it may have been moved. */
1039 static int usbfs_scan_busdir(struct libusb_context *ctx,
1040 struct discovered_devs **_discdevs, uint8_t busnum)
1042 DIR *dir;
1043 char dirpath[PATH_MAX];
1044 struct dirent *entry;
1045 struct discovered_devs *discdevs = *_discdevs;
1046 int r = LIBUSB_ERROR_IO;
1048 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1049 usbi_dbg("%s", dirpath);
1050 dir = opendir(dirpath);
1051 if (!dir) {
1052 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1053 /* FIXME: should handle valid race conditions like hub unplugged
1054 * during directory iteration - this is not an error */
1055 return r;
1058 while ((entry = readdir(dir))) {
1059 int devaddr;
1061 if (entry->d_name[0] == '.')
1062 continue;
1064 devaddr = atoi(entry->d_name);
1065 if (devaddr == 0) {
1066 usbi_dbg("unknown dir entry %s", entry->d_name);
1067 continue;
1070 if (enumerate_device(ctx, &discdevs, busnum, (uint8_t) devaddr, NULL)) {
1071 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1072 continue;
1075 r = 0;
1078 if (!r)
1079 *_discdevs = discdevs;
1080 closedir(dir);
1081 return r;
1084 static int usbfs_get_device_list(struct libusb_context *ctx,
1085 struct discovered_devs **_discdevs)
1087 struct dirent *entry;
1088 DIR *buses = opendir(usbfs_path);
1089 struct discovered_devs *discdevs = *_discdevs;
1090 int r = 0;
1092 if (!buses) {
1093 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1094 return LIBUSB_ERROR_IO;
1097 while ((entry = readdir(buses))) {
1098 struct discovered_devs *discdevs_new = discdevs;
1099 int busnum;
1101 if (entry->d_name[0] == '.')
1102 continue;
1104 if (usbdev_names) {
1105 int devaddr;
1106 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1107 continue;
1109 r = enumerate_device(ctx, &discdevs_new, busnum,
1110 (uint8_t) devaddr, NULL);
1111 if (r < 0) {
1112 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1113 continue;
1115 } else {
1116 busnum = atoi(entry->d_name);
1117 if (busnum == 0) {
1118 usbi_dbg("unknown dir entry %s", entry->d_name);
1119 continue;
1122 r = usbfs_scan_busdir(ctx, &discdevs_new, busnum);
1123 if (r < 0)
1124 goto out;
1126 discdevs = discdevs_new;
1129 out:
1130 closedir(buses);
1131 *_discdevs = discdevs;
1132 return r;
1136 static int sysfs_scan_device(struct libusb_context *ctx,
1137 struct discovered_devs **_discdevs, const char *devname)
1139 int busnum;
1140 int devaddr;
1142 usbi_dbg("scan %s", devname);
1144 busnum = __read_sysfs_attr(ctx, devname, "busnum");
1145 if (busnum < 0)
1146 return busnum;
1148 devaddr = __read_sysfs_attr(ctx, devname, "devnum");
1149 if (devaddr < 0)
1150 return devaddr;
1152 usbi_dbg("bus=%d dev=%d", busnum, devaddr);
1153 if (busnum > 255 || devaddr > 255)
1154 return LIBUSB_ERROR_INVALID_PARAM;
1156 return enumerate_device(ctx, _discdevs, busnum & 0xff, devaddr & 0xff,
1157 devname);
1160 static void sysfs_analyze_topology(struct discovered_devs *discdevs)
1162 struct linux_device_priv *priv;
1163 int i, j;
1164 struct libusb_device *dev1, *dev2;
1165 const char *sysfs_dir1, *sysfs_dir2;
1166 const char *p;
1167 int n, boundary_char;
1169 /* Fill in the port_number and parent_dev fields for each device */
1171 for (i = 0; i < discdevs->len; ++i) {
1172 dev1 = discdevs->devices[i];
1173 priv = _device_priv(dev1);
1174 if (!priv)
1175 continue;
1176 sysfs_dir1 = priv->sysfs_dir;
1178 /* Root hubs have sysfs_dir names of the form "usbB",
1179 * where B is the bus number. All other devices have
1180 * sysfs_dir names of the form "B-P[.P ...]", where the
1181 * P values are port numbers leading from the root hub
1182 * to the device.
1185 /* Root hubs don't have parents or port numbers */
1186 if (sysfs_dir1[0] == 'u')
1187 continue;
1189 /* The rightmost component is the device's port number */
1190 p = strrchr(sysfs_dir1, '.');
1191 if (!p) {
1192 p = strchr(sysfs_dir1, '-');
1193 if (!p)
1194 continue; /* Should never happen */
1196 dev1->port_number = atoi(p + 1);
1198 /* Search for the parent device */
1199 boundary_char = *p;
1200 n = p - sysfs_dir1;
1201 for (j = 0; j < discdevs->len; ++j) {
1202 dev2 = discdevs->devices[j];
1203 priv = _device_priv(dev2);
1204 if (!priv)
1205 continue;
1206 sysfs_dir2 = priv->sysfs_dir;
1208 if (boundary_char == '-') {
1209 /* The parent's name must begin with 'usb';
1210 * skip past that part of sysfs_dir2.
1212 if (sysfs_dir2[0] != 'u')
1213 continue;
1214 sysfs_dir2 += 3;
1217 /* The remainder of the parent's name must be equal to
1218 * the first n bytes of sysfs_dir1.
1220 if (memcmp(sysfs_dir1, sysfs_dir2, n) == 0 && !sysfs_dir2[n]) {
1221 dev1->parent_dev = dev2;
1222 break;
1228 static int sysfs_get_device_list(struct libusb_context *ctx,
1229 struct discovered_devs **_discdevs)
1231 struct discovered_devs *discdevs = *_discdevs;
1232 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1233 struct dirent *entry;
1234 int r = LIBUSB_ERROR_IO;
1236 if (!devices) {
1237 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1238 return r;
1241 while ((entry = readdir(devices))) {
1242 struct discovered_devs *discdevs_new = discdevs;
1244 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1245 || strchr(entry->d_name, ':'))
1246 continue;
1248 if (sysfs_scan_device(ctx, &discdevs_new, entry->d_name)) {
1249 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1250 continue;
1253 r = 0;
1254 discdevs = discdevs_new;
1257 if (!r)
1258 *_discdevs = discdevs;
1259 closedir(devices);
1260 sysfs_analyze_topology(discdevs);
1261 return r;
1264 static int op_get_device_list(struct libusb_context *ctx,
1265 struct discovered_devs **_discdevs)
1267 /* we can retrieve device list and descriptors from sysfs or usbfs.
1268 * sysfs is preferable, because if we use usbfs we end up resuming
1269 * any autosuspended USB devices. however, sysfs is not available
1270 * everywhere, so we need a usbfs fallback too.
1272 * as described in the "sysfs vs usbfs" comment at the top of this
1273 * file, sometimes we have sysfs but not enough information to
1274 * relate sysfs devices to usbfs nodes. op_init() determines the
1275 * adequacy of sysfs and sets sysfs_can_relate_devices.
1277 if (sysfs_can_relate_devices != 0)
1278 return sysfs_get_device_list(ctx, _discdevs);
1279 else
1280 return usbfs_get_device_list(ctx, _discdevs);
1283 static int op_open(struct libusb_device_handle *handle)
1285 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1286 char filename[PATH_MAX];
1287 int r;
1289 _get_usbfs_path(handle->dev, filename);
1290 usbi_dbg("opening %s", filename);
1291 hpriv->fd = open(filename, O_RDWR);
1292 if (hpriv->fd < 0) {
1293 if (errno == EACCES) {
1294 usbi_err(HANDLE_CTX(handle), "libusbx couldn't open USB device %s: "
1295 "Permission denied.", filename);
1296 usbi_err(HANDLE_CTX(handle),
1297 "libusbx requires write access to USB device nodes.");
1298 return LIBUSB_ERROR_ACCESS;
1299 } else if (errno == ENOENT) {
1300 usbi_err(HANDLE_CTX(handle), "libusbx couldn't open USB device %s: "
1301 "No such file or directory.", filename);
1302 return LIBUSB_ERROR_NO_DEVICE;
1303 } else {
1304 usbi_err(HANDLE_CTX(handle),
1305 "open failed, code %d errno %d", hpriv->fd, errno);
1306 return LIBUSB_ERROR_IO;
1310 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1311 if (r < 0) {
1312 if (errno == ENOTTY)
1313 usbi_dbg("%s: getcap not available", filename);
1314 else
1315 usbi_err(HANDLE_CTX(handle),
1316 "%s: getcap failed (%d)", filename, errno);
1317 hpriv->caps = 0;
1318 if (supports_flag_zero_packet)
1319 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1320 if (supports_flag_bulk_continuation)
1321 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1324 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1327 static void op_close(struct libusb_device_handle *dev_handle)
1329 int fd = _device_handle_priv(dev_handle)->fd;
1330 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1331 close(fd);
1334 static int op_get_configuration(struct libusb_device_handle *handle,
1335 int *config)
1337 int r;
1338 if (sysfs_can_relate_devices != 1)
1339 return LIBUSB_ERROR_NOT_SUPPORTED;
1341 r = sysfs_get_active_config(handle->dev, config);
1342 if (r < 0)
1343 return r;
1345 if (*config == -1) {
1346 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1347 *config = 0;
1350 return 0;
1353 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1355 struct linux_device_priv *priv = _device_priv(handle->dev);
1356 int fd = _device_handle_priv(handle)->fd;
1357 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1358 if (r) {
1359 if (errno == EINVAL)
1360 return LIBUSB_ERROR_NOT_FOUND;
1361 else if (errno == EBUSY)
1362 return LIBUSB_ERROR_BUSY;
1363 else if (errno == ENODEV)
1364 return LIBUSB_ERROR_NO_DEVICE;
1366 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1367 return LIBUSB_ERROR_OTHER;
1370 if (!sysfs_has_descriptors) {
1371 /* update our cached active config descriptor */
1372 if (config == -1) {
1373 if (priv->config_descriptor) {
1374 free(priv->config_descriptor);
1375 priv->config_descriptor = NULL;
1377 } else {
1378 r = cache_active_config(handle->dev, fd, config);
1379 if (r < 0)
1380 usbi_warn(HANDLE_CTX(handle),
1381 "failed to update cached config descriptor, error %d", r);
1385 return 0;
1388 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1390 int fd = _device_handle_priv(handle)->fd;
1391 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1392 if (r) {
1393 if (errno == ENOENT)
1394 return LIBUSB_ERROR_NOT_FOUND;
1395 else if (errno == EBUSY)
1396 return LIBUSB_ERROR_BUSY;
1397 else if (errno == ENODEV)
1398 return LIBUSB_ERROR_NO_DEVICE;
1400 usbi_err(HANDLE_CTX(handle),
1401 "claim interface failed, error %d errno %d", r, errno);
1402 return LIBUSB_ERROR_OTHER;
1404 return 0;
1407 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1409 int fd = _device_handle_priv(handle)->fd;
1410 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1411 if (r) {
1412 if (errno == ENODEV)
1413 return LIBUSB_ERROR_NO_DEVICE;
1415 usbi_err(HANDLE_CTX(handle),
1416 "release interface failed, error %d errno %d", r, errno);
1417 return LIBUSB_ERROR_OTHER;
1419 return 0;
1422 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1423 int altsetting)
1425 int fd = _device_handle_priv(handle)->fd;
1426 struct usbfs_setinterface setintf;
1427 int r;
1429 setintf.interface = iface;
1430 setintf.altsetting = altsetting;
1431 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1432 if (r) {
1433 if (errno == EINVAL)
1434 return LIBUSB_ERROR_NOT_FOUND;
1435 else if (errno == ENODEV)
1436 return LIBUSB_ERROR_NO_DEVICE;
1438 usbi_err(HANDLE_CTX(handle),
1439 "setintf failed error %d errno %d", r, errno);
1440 return LIBUSB_ERROR_OTHER;
1443 return 0;
1446 static int op_clear_halt(struct libusb_device_handle *handle,
1447 unsigned char endpoint)
1449 int fd = _device_handle_priv(handle)->fd;
1450 unsigned int _endpoint = endpoint;
1451 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1452 if (r) {
1453 if (errno == ENOENT)
1454 return LIBUSB_ERROR_NOT_FOUND;
1455 else if (errno == ENODEV)
1456 return LIBUSB_ERROR_NO_DEVICE;
1458 usbi_err(HANDLE_CTX(handle),
1459 "clear_halt failed error %d errno %d", r, errno);
1460 return LIBUSB_ERROR_OTHER;
1463 return 0;
1466 static int op_reset_device(struct libusb_device_handle *handle)
1468 int fd = _device_handle_priv(handle)->fd;
1469 int i, r, ret = 0;
1471 /* Doing a device reset will cause the usbfs driver to get unbound
1472 from any interfaces it is bound to. By voluntarily unbinding
1473 the usbfs driver ourself, we stop the kernel from rebinding
1474 the interface after reset (which would end up with the interface
1475 getting bound to the in kernel driver if any). */
1476 for (i = 0; i < USB_MAXINTERFACES; i++) {
1477 if (handle->claimed_interfaces & (1L << i)) {
1478 op_release_interface(handle, i);
1482 usbi_mutex_lock(&handle->lock);
1483 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1484 if (r) {
1485 if (errno == ENODEV) {
1486 ret = LIBUSB_ERROR_NOT_FOUND;
1487 goto out;
1490 usbi_err(HANDLE_CTX(handle),
1491 "reset failed error %d errno %d", r, errno);
1492 ret = LIBUSB_ERROR_OTHER;
1493 goto out;
1496 /* And re-claim any interfaces which were claimed before the reset */
1497 for (i = 0; i < USB_MAXINTERFACES; i++) {
1498 if (handle->claimed_interfaces & (1L << i)) {
1499 r = op_claim_interface(handle, i);
1500 if (r) {
1501 usbi_warn(HANDLE_CTX(handle),
1502 "failed to re-claim interface %d after reset", i);
1503 handle->claimed_interfaces &= ~(1L << i);
1507 out:
1508 usbi_mutex_unlock(&handle->lock);
1509 return ret;
1512 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1513 int interface)
1515 int fd = _device_handle_priv(handle)->fd;
1516 struct usbfs_getdriver getdrv;
1517 int r;
1519 getdrv.interface = interface;
1520 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1521 if (r) {
1522 if (errno == ENODATA)
1523 return 0;
1524 else if (errno == ENODEV)
1525 return LIBUSB_ERROR_NO_DEVICE;
1527 usbi_err(HANDLE_CTX(handle),
1528 "get driver failed error %d errno %d", r, errno);
1529 return LIBUSB_ERROR_OTHER;
1532 return 1;
1535 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1536 int interface)
1538 int fd = _device_handle_priv(handle)->fd;
1539 struct usbfs_ioctl command;
1540 struct usbfs_getdriver getdrv;
1541 int r;
1543 command.ifno = interface;
1544 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1545 command.data = NULL;
1547 getdrv.interface = interface;
1548 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1549 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1550 return LIBUSB_ERROR_NOT_FOUND;
1552 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1553 if (r) {
1554 if (errno == ENODATA)
1555 return LIBUSB_ERROR_NOT_FOUND;
1556 else if (errno == EINVAL)
1557 return LIBUSB_ERROR_INVALID_PARAM;
1558 else if (errno == ENODEV)
1559 return LIBUSB_ERROR_NO_DEVICE;
1561 usbi_err(HANDLE_CTX(handle),
1562 "detach failed error %d errno %d", r, errno);
1563 return LIBUSB_ERROR_OTHER;
1566 return 0;
1569 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1570 int interface)
1572 int fd = _device_handle_priv(handle)->fd;
1573 struct usbfs_ioctl command;
1574 int r;
1576 command.ifno = interface;
1577 command.ioctl_code = IOCTL_USBFS_CONNECT;
1578 command.data = NULL;
1580 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1581 if (r < 0) {
1582 if (errno == ENODATA)
1583 return LIBUSB_ERROR_NOT_FOUND;
1584 else if (errno == EINVAL)
1585 return LIBUSB_ERROR_INVALID_PARAM;
1586 else if (errno == ENODEV)
1587 return LIBUSB_ERROR_NO_DEVICE;
1588 else if (errno == EBUSY)
1589 return LIBUSB_ERROR_BUSY;
1591 usbi_err(HANDLE_CTX(handle),
1592 "attach failed error %d errno %d", r, errno);
1593 return LIBUSB_ERROR_OTHER;
1594 } else if (r == 0) {
1595 return LIBUSB_ERROR_NOT_FOUND;
1598 return 0;
1601 static void op_destroy_device(struct libusb_device *dev)
1603 struct linux_device_priv *priv = _device_priv(dev);
1604 if (!sysfs_has_descriptors) {
1605 if (priv->dev_descriptor)
1606 free(priv->dev_descriptor);
1607 if (priv->config_descriptor)
1608 free(priv->config_descriptor);
1610 if (priv->sysfs_dir)
1611 free(priv->sysfs_dir);
1614 /* URBs are discarded in reverse order of submission to avoid races. */
1615 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1617 struct libusb_transfer *transfer =
1618 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1619 struct linux_transfer_priv *tpriv =
1620 usbi_transfer_get_os_priv(itransfer);
1621 struct linux_device_handle_priv *dpriv =
1622 _device_handle_priv(transfer->dev_handle);
1623 int i, ret = 0;
1624 struct usbfs_urb *urb;
1626 for (i = last_plus_one - 1; i >= first; i--) {
1627 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1628 urb = tpriv->iso_urbs[i];
1629 else
1630 urb = &tpriv->urbs[i];
1632 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1633 continue;
1635 if (EINVAL == errno) {
1636 usbi_dbg("URB not found --> assuming ready to be reaped");
1637 if (i == (last_plus_one - 1))
1638 ret = LIBUSB_ERROR_NOT_FOUND;
1639 } else if (ENODEV == errno) {
1640 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1641 ret = LIBUSB_ERROR_NO_DEVICE;
1642 } else {
1643 usbi_warn(TRANSFER_CTX(transfer),
1644 "unrecognised discard errno %d", errno);
1645 ret = LIBUSB_ERROR_OTHER;
1648 return ret;
1651 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1653 int i;
1654 for (i = 0; i < tpriv->num_urbs; i++) {
1655 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1656 if (!urb)
1657 break;
1658 free(urb);
1661 free(tpriv->iso_urbs);
1662 tpriv->iso_urbs = NULL;
1665 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1666 unsigned char urb_type)
1668 struct libusb_transfer *transfer =
1669 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1670 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1671 struct linux_device_handle_priv *dpriv =
1672 _device_handle_priv(transfer->dev_handle);
1673 struct usbfs_urb *urbs;
1674 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1675 == LIBUSB_ENDPOINT_OUT;
1676 int bulk_buffer_len, use_bulk_continuation;
1677 int r;
1678 int i;
1679 size_t alloc_size;
1681 if (tpriv->urbs)
1682 return LIBUSB_ERROR_BUSY;
1684 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1685 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1686 return LIBUSB_ERROR_NOT_SUPPORTED;
1689 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1690 * around this by splitting large transfers into 16k blocks, and then
1691 * submit all urbs at once. it would be simpler to submit one urb at
1692 * a time, but there is a big performance gain doing it this way.
1694 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1695 * using arbritary large transfers can still be a bad idea though, as
1696 * the kernel needs to allocate physical contiguous memory for this,
1697 * which may fail for large buffers.
1699 * The kernel solves this problem by splitting the transfer into
1700 * blocks itself when the host-controller is scatter-gather capable
1701 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1703 * Last, there is the issue of short-transfers when splitting, for
1704 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1705 * is needed, but this is not always available.
1707 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1708 /* Good! Just submit everything in one go */
1709 bulk_buffer_len = transfer->length ? transfer->length : 1;
1710 use_bulk_continuation = 0;
1711 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1712 /* Split the transfers and use bulk-continuation to
1713 avoid issues with short-transfers */
1714 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1715 use_bulk_continuation = 1;
1716 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1717 /* Don't split, assume the kernel can alloc the buffer
1718 (otherwise the submit will fail with -ENOMEM) */
1719 bulk_buffer_len = transfer->length ? transfer->length : 1;
1720 use_bulk_continuation = 0;
1721 } else {
1722 /* Bad, splitting without bulk-continuation, short transfers
1723 which end before the last urb will not work reliable! */
1724 /* Note we don't warn here as this is "normal" on kernels <
1725 2.6.32 and not a problem for most applications */
1726 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1727 use_bulk_continuation = 0;
1730 int num_urbs = transfer->length / bulk_buffer_len;
1731 int last_urb_partial = 0;
1733 if (transfer->length == 0) {
1734 num_urbs = 1;
1735 } else if ((transfer->length % bulk_buffer_len) > 0) {
1736 last_urb_partial = 1;
1737 num_urbs++;
1739 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1740 transfer->length);
1741 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1742 urbs = calloc(1, alloc_size);
1743 if (!urbs)
1744 return LIBUSB_ERROR_NO_MEM;
1745 tpriv->urbs = urbs;
1746 tpriv->num_urbs = num_urbs;
1747 tpriv->num_retired = 0;
1748 tpriv->reap_action = NORMAL;
1749 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1751 for (i = 0; i < num_urbs; i++) {
1752 struct usbfs_urb *urb = &urbs[i];
1753 urb->usercontext = itransfer;
1754 urb->type = urb_type;
1755 urb->endpoint = transfer->endpoint;
1756 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1757 if (use_bulk_continuation && !is_out && (i != num_urbs - 1))
1758 urb->flags = USBFS_URB_SHORT_NOT_OK;
1759 if (i == num_urbs - 1 && last_urb_partial)
1760 urb->buffer_length = transfer->length % bulk_buffer_len;
1761 else if (transfer->length == 0)
1762 urb->buffer_length = 0;
1763 else
1764 urb->buffer_length = bulk_buffer_len;
1766 if (i > 0 && use_bulk_continuation)
1767 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1769 /* we have already checked that the flag is supported */
1770 if (is_out && i == num_urbs - 1 &&
1771 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1772 urb->flags |= USBFS_URB_ZERO_PACKET;
1774 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1775 if (r < 0) {
1776 if (errno == ENODEV) {
1777 r = LIBUSB_ERROR_NO_DEVICE;
1778 } else {
1779 usbi_err(TRANSFER_CTX(transfer),
1780 "submiturb failed error %d errno=%d", r, errno);
1781 r = LIBUSB_ERROR_IO;
1784 /* if the first URB submission fails, we can simply free up and
1785 * return failure immediately. */
1786 if (i == 0) {
1787 usbi_dbg("first URB failed, easy peasy");
1788 free(urbs);
1789 tpriv->urbs = NULL;
1790 return r;
1793 /* if it's not the first URB that failed, the situation is a bit
1794 * tricky. we may need to discard all previous URBs. there are
1795 * complications:
1796 * - discarding is asynchronous - discarded urbs will be reaped
1797 * later. the user must not have freed the transfer when the
1798 * discarded URBs are reaped, otherwise libusbx will be using
1799 * freed memory.
1800 * - the earlier URBs may have completed successfully and we do
1801 * not want to throw away any data.
1802 * - this URB failing may be no error; EREMOTEIO means that
1803 * this transfer simply didn't need all the URBs we submitted
1804 * so, we report that the transfer was submitted successfully and
1805 * in case of error we discard all previous URBs. later when
1806 * the final reap completes we can report error to the user,
1807 * or success if an earlier URB was completed successfully.
1809 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1811 /* The URBs we haven't submitted yet we count as already
1812 * retired. */
1813 tpriv->num_retired += num_urbs - i;
1815 /* If we completed short then don't try to discard. */
1816 if (COMPLETED_EARLY == tpriv->reap_action)
1817 return 0;
1819 discard_urbs(itransfer, 0, i);
1821 usbi_dbg("reporting successful submission but waiting for %d "
1822 "discards before reporting error", i);
1823 return 0;
1827 return 0;
1830 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1832 struct libusb_transfer *transfer =
1833 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1834 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1835 struct linux_device_handle_priv *dpriv =
1836 _device_handle_priv(transfer->dev_handle);
1837 struct usbfs_urb **urbs;
1838 size_t alloc_size;
1839 int num_packets = transfer->num_iso_packets;
1840 int i;
1841 int this_urb_len = 0;
1842 int num_urbs = 1;
1843 int packet_offset = 0;
1844 unsigned int packet_len;
1845 unsigned char *urb_buffer = transfer->buffer;
1847 if (tpriv->iso_urbs)
1848 return LIBUSB_ERROR_BUSY;
1850 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1851 * into smaller units to meet such restriction, then fire off all the
1852 * units at once. it would be simpler if we just fired one unit at a time,
1853 * but there is a big performance gain through doing it this way.
1855 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1856 * using arbritary large transfers is still be a bad idea though, as
1857 * the kernel needs to allocate physical contiguous memory for this,
1858 * which may fail for large buffers.
1861 /* calculate how many URBs we need */
1862 for (i = 0; i < num_packets; i++) {
1863 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1864 packet_len = transfer->iso_packet_desc[i].length;
1866 if (packet_len > space_remaining) {
1867 num_urbs++;
1868 this_urb_len = packet_len;
1869 } else {
1870 this_urb_len += packet_len;
1873 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1875 alloc_size = num_urbs * sizeof(*urbs);
1876 urbs = calloc(1, alloc_size);
1877 if (!urbs)
1878 return LIBUSB_ERROR_NO_MEM;
1880 tpriv->iso_urbs = urbs;
1881 tpriv->num_urbs = num_urbs;
1882 tpriv->num_retired = 0;
1883 tpriv->reap_action = NORMAL;
1884 tpriv->iso_packet_offset = 0;
1886 /* allocate + initialize each URB with the correct number of packets */
1887 for (i = 0; i < num_urbs; i++) {
1888 struct usbfs_urb *urb;
1889 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1890 int urb_packet_offset = 0;
1891 unsigned char *urb_buffer_orig = urb_buffer;
1892 int j;
1893 int k;
1895 /* swallow up all the packets we can fit into this URB */
1896 while (packet_offset < transfer->num_iso_packets) {
1897 packet_len = transfer->iso_packet_desc[packet_offset].length;
1898 if (packet_len <= space_remaining_in_urb) {
1899 /* throw it in */
1900 urb_packet_offset++;
1901 packet_offset++;
1902 space_remaining_in_urb -= packet_len;
1903 urb_buffer += packet_len;
1904 } else {
1905 /* it can't fit, save it for the next URB */
1906 break;
1910 alloc_size = sizeof(*urb)
1911 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1912 urb = calloc(1, alloc_size);
1913 if (!urb) {
1914 free_iso_urbs(tpriv);
1915 return LIBUSB_ERROR_NO_MEM;
1917 urbs[i] = urb;
1919 /* populate packet lengths */
1920 for (j = 0, k = packet_offset - urb_packet_offset;
1921 k < packet_offset; k++, j++) {
1922 packet_len = transfer->iso_packet_desc[k].length;
1923 urb->iso_frame_desc[j].length = packet_len;
1926 urb->usercontext = itransfer;
1927 urb->type = USBFS_URB_TYPE_ISO;
1928 /* FIXME: interface for non-ASAP data? */
1929 urb->flags = USBFS_URB_ISO_ASAP;
1930 urb->endpoint = transfer->endpoint;
1931 urb->number_of_packets = urb_packet_offset;
1932 urb->buffer = urb_buffer_orig;
1935 /* submit URBs */
1936 for (i = 0; i < num_urbs; i++) {
1937 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1938 if (r < 0) {
1939 if (errno == ENODEV) {
1940 r = LIBUSB_ERROR_NO_DEVICE;
1941 } else {
1942 usbi_err(TRANSFER_CTX(transfer),
1943 "submiturb failed error %d errno=%d", r, errno);
1944 r = LIBUSB_ERROR_IO;
1947 /* if the first URB submission fails, we can simply free up and
1948 * return failure immediately. */
1949 if (i == 0) {
1950 usbi_dbg("first URB failed, easy peasy");
1951 free_iso_urbs(tpriv);
1952 return r;
1955 /* if it's not the first URB that failed, the situation is a bit
1956 * tricky. we must discard all previous URBs. there are
1957 * complications:
1958 * - discarding is asynchronous - discarded urbs will be reaped
1959 * later. the user must not have freed the transfer when the
1960 * discarded URBs are reaped, otherwise libusbx will be using
1961 * freed memory.
1962 * - the earlier URBs may have completed successfully and we do
1963 * not want to throw away any data.
1964 * so, in this case we discard all the previous URBs BUT we report
1965 * that the transfer was submitted successfully. then later when
1966 * the final discard completes we can report error to the user.
1968 tpriv->reap_action = SUBMIT_FAILED;
1970 /* The URBs we haven't submitted yet we count as already
1971 * retired. */
1972 tpriv->num_retired = num_urbs - i;
1973 discard_urbs(itransfer, 0, i);
1975 usbi_dbg("reporting successful submission but waiting for %d "
1976 "discards before reporting error", i);
1977 return 0;
1981 return 0;
1984 static int submit_control_transfer(struct usbi_transfer *itransfer)
1986 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1987 struct libusb_transfer *transfer =
1988 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1989 struct linux_device_handle_priv *dpriv =
1990 _device_handle_priv(transfer->dev_handle);
1991 struct usbfs_urb *urb;
1992 int r;
1994 if (tpriv->urbs)
1995 return LIBUSB_ERROR_BUSY;
1997 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1998 return LIBUSB_ERROR_INVALID_PARAM;
2000 urb = calloc(1, sizeof(struct usbfs_urb));
2001 if (!urb)
2002 return LIBUSB_ERROR_NO_MEM;
2003 tpriv->urbs = urb;
2004 tpriv->num_urbs = 1;
2005 tpriv->reap_action = NORMAL;
2007 urb->usercontext = itransfer;
2008 urb->type = USBFS_URB_TYPE_CONTROL;
2009 urb->endpoint = transfer->endpoint;
2010 urb->buffer = transfer->buffer;
2011 urb->buffer_length = transfer->length;
2013 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2014 if (r < 0) {
2015 free(urb);
2016 tpriv->urbs = NULL;
2017 if (errno == ENODEV)
2018 return LIBUSB_ERROR_NO_DEVICE;
2020 usbi_err(TRANSFER_CTX(transfer),
2021 "submiturb failed error %d errno=%d", r, errno);
2022 return LIBUSB_ERROR_IO;
2024 return 0;
2027 static int op_submit_transfer(struct usbi_transfer *itransfer)
2029 struct libusb_transfer *transfer =
2030 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2032 switch (transfer->type) {
2033 case LIBUSB_TRANSFER_TYPE_CONTROL:
2034 return submit_control_transfer(itransfer);
2035 case LIBUSB_TRANSFER_TYPE_BULK:
2036 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2037 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2038 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2039 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2040 return submit_iso_transfer(itransfer);
2041 default:
2042 usbi_err(TRANSFER_CTX(transfer),
2043 "unknown endpoint type %d", transfer->type);
2044 return LIBUSB_ERROR_INVALID_PARAM;
2048 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2050 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2051 struct libusb_transfer *transfer =
2052 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2054 switch (transfer->type) {
2055 case LIBUSB_TRANSFER_TYPE_BULK:
2056 if (tpriv->reap_action == ERROR)
2057 break;
2058 /* else, fall through */
2059 case LIBUSB_TRANSFER_TYPE_CONTROL:
2060 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2061 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2062 tpriv->reap_action = CANCELLED;
2063 break;
2064 default:
2065 usbi_err(TRANSFER_CTX(transfer),
2066 "unknown endpoint type %d", transfer->type);
2067 return LIBUSB_ERROR_INVALID_PARAM;
2070 if (!tpriv->urbs)
2071 return LIBUSB_ERROR_NOT_FOUND;
2073 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2076 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2078 struct libusb_transfer *transfer =
2079 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2080 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2082 /* urbs can be freed also in submit_transfer so lock mutex first */
2083 switch (transfer->type) {
2084 case LIBUSB_TRANSFER_TYPE_CONTROL:
2085 case LIBUSB_TRANSFER_TYPE_BULK:
2086 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2087 usbi_mutex_lock(&itransfer->lock);
2088 if (tpriv->urbs)
2089 free(tpriv->urbs);
2090 tpriv->urbs = NULL;
2091 usbi_mutex_unlock(&itransfer->lock);
2092 break;
2093 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2094 usbi_mutex_lock(&itransfer->lock);
2095 if (tpriv->iso_urbs)
2096 free_iso_urbs(tpriv);
2097 usbi_mutex_unlock(&itransfer->lock);
2098 break;
2099 default:
2100 usbi_err(TRANSFER_CTX(transfer),
2101 "unknown endpoint type %d", transfer->type);
2105 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2106 struct usbfs_urb *urb)
2108 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2109 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2110 int urb_idx = urb - tpriv->urbs;
2112 usbi_mutex_lock(&itransfer->lock);
2113 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2114 urb_idx + 1, tpriv->num_urbs);
2116 tpriv->num_retired++;
2118 if (tpriv->reap_action != NORMAL) {
2119 /* cancelled, submit_fail, or completed early */
2120 usbi_dbg("abnormal reap: urb status %d", urb->status);
2122 /* even though we're in the process of cancelling, it's possible that
2123 * we may receive some data in these URBs that we don't want to lose.
2124 * examples:
2125 * 1. while the kernel is cancelling all the packets that make up an
2126 * URB, a few of them might complete. so we get back a successful
2127 * cancellation *and* some data.
2128 * 2. we receive a short URB which marks the early completion condition,
2129 * so we start cancelling the remaining URBs. however, we're too
2130 * slow and another URB completes (or at least completes partially).
2131 * (this can't happen since we always use BULK_CONTINUATION.)
2133 * When this happens, our objectives are not to lose any "surplus" data,
2134 * and also to stick it at the end of the previously-received data
2135 * (closing any holes), so that libusbx reports the total amount of
2136 * transferred data and presents it in a contiguous chunk.
2138 if (urb->actual_length > 0) {
2139 unsigned char *target = transfer->buffer + itransfer->transferred;
2140 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2141 if (urb->buffer != target) {
2142 usbi_dbg("moving surplus data from offset %d to offset %d",
2143 (unsigned char *) urb->buffer - transfer->buffer,
2144 target - transfer->buffer);
2145 memmove(target, urb->buffer, urb->actual_length);
2147 itransfer->transferred += urb->actual_length;
2150 if (tpriv->num_retired == tpriv->num_urbs) {
2151 usbi_dbg("abnormal reap: last URB handled, reporting");
2152 if (tpriv->reap_action != COMPLETED_EARLY &&
2153 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2154 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2155 goto completed;
2157 goto out_unlock;
2160 itransfer->transferred += urb->actual_length;
2162 /* Many of these errors can occur on *any* urb of a multi-urb
2163 * transfer. When they do, we tear down the rest of the transfer.
2165 switch (urb->status) {
2166 case 0:
2167 break;
2168 case -EREMOTEIO: /* short transfer */
2169 break;
2170 case -ENOENT: /* cancelled */
2171 case -ECONNRESET:
2172 break;
2173 case -ENODEV:
2174 case -ESHUTDOWN:
2175 usbi_dbg("device removed");
2176 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2177 goto cancel_remaining;
2178 case -EPIPE:
2179 usbi_dbg("detected endpoint stall");
2180 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2181 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2182 goto cancel_remaining;
2183 case -EOVERFLOW:
2184 /* overflow can only ever occur in the last urb */
2185 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2186 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2187 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2188 goto completed;
2189 case -ETIME:
2190 case -EPROTO:
2191 case -EILSEQ:
2192 case -ECOMM:
2193 case -ENOSR:
2194 usbi_dbg("low level error %d", urb->status);
2195 tpriv->reap_action = ERROR;
2196 goto cancel_remaining;
2197 default:
2198 usbi_warn(ITRANSFER_CTX(itransfer),
2199 "unrecognised urb status %d", urb->status);
2200 tpriv->reap_action = ERROR;
2201 goto cancel_remaining;
2204 /* if we're the last urb or we got less data than requested then we're
2205 * done */
2206 if (urb_idx == tpriv->num_urbs - 1) {
2207 usbi_dbg("last URB in transfer --> complete!");
2208 goto completed;
2209 } else if (urb->actual_length < urb->buffer_length) {
2210 usbi_dbg("short transfer %d/%d --> complete!",
2211 urb->actual_length, urb->buffer_length);
2212 if (tpriv->reap_action == NORMAL)
2213 tpriv->reap_action = COMPLETED_EARLY;
2214 } else
2215 goto out_unlock;
2217 cancel_remaining:
2218 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2219 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2221 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2222 goto completed;
2224 /* cancel remaining urbs and wait for their completion before
2225 * reporting results */
2226 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2228 out_unlock:
2229 usbi_mutex_unlock(&itransfer->lock);
2230 return 0;
2232 completed:
2233 free(tpriv->urbs);
2234 tpriv->urbs = NULL;
2235 usbi_mutex_unlock(&itransfer->lock);
2236 return CANCELLED == tpriv->reap_action ?
2237 usbi_handle_transfer_cancellation(itransfer) :
2238 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2241 static int handle_iso_completion(struct usbi_transfer *itransfer,
2242 struct usbfs_urb *urb)
2244 struct libusb_transfer *transfer =
2245 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2246 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2247 int num_urbs = tpriv->num_urbs;
2248 int urb_idx = 0;
2249 int i;
2250 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2252 usbi_mutex_lock(&itransfer->lock);
2253 for (i = 0; i < num_urbs; i++) {
2254 if (urb == tpriv->iso_urbs[i]) {
2255 urb_idx = i + 1;
2256 break;
2259 if (urb_idx == 0) {
2260 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2261 usbi_mutex_unlock(&itransfer->lock);
2262 return LIBUSB_ERROR_NOT_FOUND;
2265 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2266 urb_idx, num_urbs);
2268 /* copy isochronous results back in */
2270 for (i = 0; i < urb->number_of_packets; i++) {
2271 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2272 struct libusb_iso_packet_descriptor *lib_desc =
2273 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2274 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2275 switch (urb_desc->status) {
2276 case 0:
2277 break;
2278 case -ENOENT: /* cancelled */
2279 case -ECONNRESET:
2280 break;
2281 case -ENODEV:
2282 case -ESHUTDOWN:
2283 usbi_dbg("device removed");
2284 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2285 break;
2286 case -EPIPE:
2287 usbi_dbg("detected endpoint stall");
2288 lib_desc->status = LIBUSB_TRANSFER_STALL;
2289 break;
2290 case -EOVERFLOW:
2291 usbi_dbg("overflow error");
2292 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2293 break;
2294 case -ETIME:
2295 case -EPROTO:
2296 case -EILSEQ:
2297 case -ECOMM:
2298 case -ENOSR:
2299 case -EXDEV:
2300 usbi_dbg("low-level USB error %d", urb_desc->status);
2301 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2302 break;
2303 default:
2304 usbi_warn(TRANSFER_CTX(transfer),
2305 "unrecognised urb status %d", urb_desc->status);
2306 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2307 break;
2309 lib_desc->actual_length = urb_desc->actual_length;
2312 tpriv->num_retired++;
2314 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2315 usbi_dbg("CANCEL: urb status %d", urb->status);
2317 if (tpriv->num_retired == num_urbs) {
2318 usbi_dbg("CANCEL: last URB handled, reporting");
2319 free_iso_urbs(tpriv);
2320 if (tpriv->reap_action == CANCELLED) {
2321 usbi_mutex_unlock(&itransfer->lock);
2322 return usbi_handle_transfer_cancellation(itransfer);
2323 } else {
2324 usbi_mutex_unlock(&itransfer->lock);
2325 return usbi_handle_transfer_completion(itransfer,
2326 LIBUSB_TRANSFER_ERROR);
2329 goto out;
2332 switch (urb->status) {
2333 case 0:
2334 break;
2335 case -ENOENT: /* cancelled */
2336 case -ECONNRESET:
2337 break;
2338 case -ESHUTDOWN:
2339 usbi_dbg("device removed");
2340 status = LIBUSB_TRANSFER_NO_DEVICE;
2341 break;
2342 default:
2343 usbi_warn(TRANSFER_CTX(transfer),
2344 "unrecognised urb status %d", urb->status);
2345 status = LIBUSB_TRANSFER_ERROR;
2346 break;
2349 /* if we're the last urb then we're done */
2350 if (urb_idx == num_urbs) {
2351 usbi_dbg("last URB in transfer --> complete!");
2352 free_iso_urbs(tpriv);
2353 usbi_mutex_unlock(&itransfer->lock);
2354 return usbi_handle_transfer_completion(itransfer, status);
2357 out:
2358 usbi_mutex_unlock(&itransfer->lock);
2359 return 0;
2362 static int handle_control_completion(struct usbi_transfer *itransfer,
2363 struct usbfs_urb *urb)
2365 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2366 int status;
2368 usbi_mutex_lock(&itransfer->lock);
2369 usbi_dbg("handling completion status %d", urb->status);
2371 itransfer->transferred += urb->actual_length;
2373 if (tpriv->reap_action == CANCELLED) {
2374 if (urb->status != 0 && urb->status != -ENOENT)
2375 usbi_warn(ITRANSFER_CTX(itransfer),
2376 "cancel: unrecognised urb status %d", urb->status);
2377 free(tpriv->urbs);
2378 tpriv->urbs = NULL;
2379 usbi_mutex_unlock(&itransfer->lock);
2380 return usbi_handle_transfer_cancellation(itransfer);
2383 switch (urb->status) {
2384 case 0:
2385 status = LIBUSB_TRANSFER_COMPLETED;
2386 break;
2387 case -ENOENT: /* cancelled */
2388 status = LIBUSB_TRANSFER_CANCELLED;
2389 break;
2390 case -ENODEV:
2391 case -ESHUTDOWN:
2392 usbi_dbg("device removed");
2393 status = LIBUSB_TRANSFER_NO_DEVICE;
2394 break;
2395 case -EPIPE:
2396 usbi_dbg("unsupported control request");
2397 status = LIBUSB_TRANSFER_STALL;
2398 break;
2399 case -EOVERFLOW:
2400 usbi_dbg("control overflow error");
2401 status = LIBUSB_TRANSFER_OVERFLOW;
2402 break;
2403 case -ETIME:
2404 case -EPROTO:
2405 case -EILSEQ:
2406 case -ECOMM:
2407 case -ENOSR:
2408 usbi_dbg("low-level bus error occurred");
2409 status = LIBUSB_TRANSFER_ERROR;
2410 break;
2411 default:
2412 usbi_warn(ITRANSFER_CTX(itransfer),
2413 "unrecognised urb status %d", urb->status);
2414 status = LIBUSB_TRANSFER_ERROR;
2415 break;
2418 free(tpriv->urbs);
2419 tpriv->urbs = NULL;
2420 usbi_mutex_unlock(&itransfer->lock);
2421 return usbi_handle_transfer_completion(itransfer, status);
2424 static int reap_for_handle(struct libusb_device_handle *handle)
2426 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2427 int r;
2428 struct usbfs_urb *urb;
2429 struct usbi_transfer *itransfer;
2430 struct libusb_transfer *transfer;
2432 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2433 if (r == -1 && errno == EAGAIN)
2434 return 1;
2435 if (r < 0) {
2436 if (errno == ENODEV)
2437 return LIBUSB_ERROR_NO_DEVICE;
2439 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2440 r, errno);
2441 return LIBUSB_ERROR_IO;
2444 itransfer = urb->usercontext;
2445 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2447 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2448 urb->actual_length);
2450 switch (transfer->type) {
2451 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2452 return handle_iso_completion(itransfer, urb);
2453 case LIBUSB_TRANSFER_TYPE_BULK:
2454 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2455 return handle_bulk_completion(itransfer, urb);
2456 case LIBUSB_TRANSFER_TYPE_CONTROL:
2457 return handle_control_completion(itransfer, urb);
2458 default:
2459 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2460 transfer->type);
2461 return LIBUSB_ERROR_OTHER;
2465 static int op_handle_events(struct libusb_context *ctx,
2466 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2468 int r;
2469 unsigned int i = 0;
2471 usbi_mutex_lock(&ctx->open_devs_lock);
2472 for (i = 0; i < nfds && num_ready > 0; i++) {
2473 struct pollfd *pollfd = &fds[i];
2474 struct libusb_device_handle *handle;
2475 struct linux_device_handle_priv *hpriv = NULL;
2477 if (!pollfd->revents)
2478 continue;
2480 num_ready--;
2481 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2482 hpriv = _device_handle_priv(handle);
2483 if (hpriv->fd == pollfd->fd)
2484 break;
2487 if (pollfd->revents & POLLERR) {
2488 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2489 usbi_handle_disconnect(handle);
2490 continue;
2493 do {
2494 r = reap_for_handle(handle);
2495 } while (r == 0);
2496 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2497 continue;
2498 else if (r < 0)
2499 goto out;
2502 r = 0;
2503 out:
2504 usbi_mutex_unlock(&ctx->open_devs_lock);
2505 return r;
2508 static int op_clock_gettime(int clk_id, struct timespec *tp)
2510 switch (clk_id) {
2511 case USBI_CLOCK_MONOTONIC:
2512 return clock_gettime(monotonic_clkid, tp);
2513 case USBI_CLOCK_REALTIME:
2514 return clock_gettime(CLOCK_REALTIME, tp);
2515 default:
2516 return LIBUSB_ERROR_INVALID_PARAM;
2520 #ifdef USBI_TIMERFD_AVAILABLE
2521 static clockid_t op_get_timerfd_clockid(void)
2523 return monotonic_clkid;
2526 #endif
2528 const struct usbi_os_backend linux_usbfs_backend = {
2529 .name = "Linux usbfs",
2530 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2531 .init = op_init,
2532 .exit = NULL,
2533 .get_device_list = op_get_device_list,
2534 .get_device_descriptor = op_get_device_descriptor,
2535 .get_active_config_descriptor = op_get_active_config_descriptor,
2536 .get_config_descriptor = op_get_config_descriptor,
2538 .open = op_open,
2539 .close = op_close,
2540 .get_configuration = op_get_configuration,
2541 .set_configuration = op_set_configuration,
2542 .claim_interface = op_claim_interface,
2543 .release_interface = op_release_interface,
2545 .set_interface_altsetting = op_set_interface,
2546 .clear_halt = op_clear_halt,
2547 .reset_device = op_reset_device,
2549 .kernel_driver_active = op_kernel_driver_active,
2550 .detach_kernel_driver = op_detach_kernel_driver,
2551 .attach_kernel_driver = op_attach_kernel_driver,
2553 .destroy_device = op_destroy_device,
2555 .submit_transfer = op_submit_transfer,
2556 .cancel_transfer = op_cancel_transfer,
2557 .clear_transfer_priv = op_clear_transfer_priv,
2559 .handle_events = op_handle_events,
2561 .clock_gettime = op_clock_gettime,
2563 #ifdef USBI_TIMERFD_AVAILABLE
2564 .get_timerfd_clockid = op_get_timerfd_clockid,
2565 #endif
2567 .device_priv_size = sizeof(struct linux_device_priv),
2568 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2569 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2570 .add_iso_packet_size = 0,