linux: Add a _get_usbfs_fd helper function
[libusbx.git] / libusb / os / linux_usbfs.c
blob49fa42d835bb95401c61f7e0ea2c4dabf97a3f1a
1 /*
2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "config.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <poll.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/utsname.h>
37 #include <unistd.h>
39 #include "libusb.h"
40 #include "libusbi.h"
41 #include "linux_usbfs.h"
43 /* sysfs vs usbfs:
44 * opening a usbfs node causes the device to be resumed, so we attempt to
45 * avoid this during enumeration.
47 * sysfs allows us to read the kernel's in-memory copies of device descriptors
48 * and so forth, avoiding the need to open the device:
49 * - The binary "descriptors" file was added in 2.6.23.
50 * - The "busnum" file was added in 2.6.22
51 * - The "devnum" file has been present since pre-2.6.18
52 * - the "bConfigurationValue" file has been present since pre-2.6.18
54 * If we have bConfigurationValue, busnum, and devnum, then we can determine
55 * the active configuration without having to open the usbfs node in RDWR mode.
56 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
57 * The busnum file is important as that is the only way we can relate sysfs
58 * devices to usbfs nodes.
60 * If we also have descriptors, we can obtain the device descriptor and active
61 * configuration without touching usbfs at all.
63 * The descriptors file originally only contained the active configuration
64 * descriptor alongside the device descriptor, but all configurations are
65 * included as of Linux 2.6.26.
68 /* endianness for multi-byte fields:
70 * Descriptors exposed by usbfs have the multi-byte fields in the device
71 * descriptor as host endian. Multi-byte fields in the other descriptors are
72 * bus-endian. The kernel documentation says otherwise, but it is wrong.
75 static const char *usbfs_path = NULL;
77 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
78 static int usbdev_names = 0;
80 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
81 * allows us to mark URBs as being part of a specific logical transfer when
82 * we submit them to the kernel. then, on any error except a cancellation, all
83 * URBs within that transfer will be cancelled and no more URBs will be
84 * accepted for the transfer, meaning that no more data can creep in.
86 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
87 * (in either direction) except the first.
88 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
89 * last; it means that the kernel should treat a short reply as an error.
90 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
91 * transfers can't be short unless there's already some sort of error), and
92 * setting this flag is disallowed (a kernel with USB debugging enabled will
93 * reject such URBs).
95 static int supports_flag_bulk_continuation = -1;
97 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
98 * allows us to mark URBs that should be followed by a zero length data
99 * packet, which can be required by device- or class-specific protocols.
101 static int supports_flag_zero_packet = -1;
103 /* clock ID for monotonic clock, as not all clock sources are available on all
104 * systems. appropriate choice made at initialization time. */
105 static clockid_t monotonic_clkid = -1;
107 /* do we have a busnum to relate devices? this also implies that we can read
108 * the active configuration through bConfigurationValue */
109 static int sysfs_can_relate_devices = 0;
111 /* do we have a descriptors file? */
112 static int sysfs_has_descriptors = 0;
114 /* how many times have we initted (and not exited) ? */
115 static volatile int init_count = 0;
117 /* Protects init_count and serializes scan_devices versus the hotplug-thread */
118 static usbi_mutex_static_t hotplug_lock = USBI_MUTEX_INITIALIZER;
120 static int linux_start_event_monitor(void);
121 static int linux_stop_event_monitor(void);
122 static int linux_scan_devices(struct libusb_context *ctx);
123 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
125 #if !defined(USE_UDEV)
126 static int linux_default_scan_devices (struct libusb_context *ctx);
127 #endif
129 struct linux_device_priv {
130 char *sysfs_dir;
131 unsigned char *dev_descriptor;
132 unsigned char *config_descriptor;
135 struct linux_device_handle_priv {
136 int fd;
137 uint32_t caps;
140 enum reap_action {
141 NORMAL = 0,
142 /* submission failed after the first URB, so await cancellation/completion
143 * of all the others */
144 SUBMIT_FAILED,
146 /* cancelled by user or timeout */
147 CANCELLED,
149 /* completed multi-URB transfer in non-final URB */
150 COMPLETED_EARLY,
152 /* one or more urbs encountered a low-level error */
153 ERROR,
156 struct linux_transfer_priv {
157 union {
158 struct usbfs_urb *urbs;
159 struct usbfs_urb **iso_urbs;
162 enum reap_action reap_action;
163 int num_urbs;
164 int num_retired;
165 enum libusb_transfer_status reap_status;
167 /* next iso packet in user-supplied transfer to be populated */
168 int iso_packet_offset;
171 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
173 struct libusb_context *ctx = DEVICE_CTX(dev);
174 char path[PATH_MAX];
175 int fd;
177 if (usbdev_names)
178 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
179 usbfs_path, dev->bus_number, dev->device_address);
180 else
181 snprintf(path, PATH_MAX, "%s/%03d/%03d",
182 usbfs_path, dev->bus_number, dev->device_address);
184 fd = open(path, mode);
185 if (fd != -1)
186 return fd; /* Success */
188 if (!silent) {
189 usbi_err(ctx, "libusbx couldn't open USB device %s: %s",
190 path, strerror(errno));
191 if (errno == EACCES && mode == O_RDWR)
192 usbi_err(ctx, "libusbx requires write access to USB "
193 "device nodes.");
196 if (errno == EACCES)
197 return LIBUSB_ERROR_ACCESS;
198 if (errno == ENOENT)
199 return LIBUSB_ERROR_NO_DEVICE;
200 return LIBUSB_ERROR_IO;
203 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
205 return (struct linux_device_priv *) dev->os_priv;
208 static struct linux_device_handle_priv *_device_handle_priv(
209 struct libusb_device_handle *handle)
211 return (struct linux_device_handle_priv *) handle->os_priv;
214 /* check dirent for a /dev/usbdev%d.%d name
215 * optionally return bus/device on success */
216 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
218 int busnum, devnum;
220 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
221 return 0;
223 usbi_dbg("found: %s", entry->d_name);
224 if (bus_p != NULL)
225 *bus_p = busnum;
226 if (dev_p != NULL)
227 *dev_p = devnum;
228 return 1;
231 static int check_usb_vfs(const char *dirname)
233 DIR *dir;
234 struct dirent *entry;
235 int found = 0;
237 dir = opendir(dirname);
238 if (!dir)
239 return 0;
241 while ((entry = readdir(dir)) != NULL) {
242 if (entry->d_name[0] == '.')
243 continue;
245 /* We assume if we find any files that it must be the right place */
246 found = 1;
247 break;
250 closedir(dir);
251 return found;
254 static const char *find_usbfs_path(void)
256 const char *path = "/dev/bus/usb";
257 const char *ret = NULL;
259 if (check_usb_vfs(path)) {
260 ret = path;
261 } else {
262 path = "/proc/bus/usb";
263 if (check_usb_vfs(path))
264 ret = path;
267 /* look for /dev/usbdev*.* if the normal places fail */
268 if (ret == NULL) {
269 struct dirent *entry;
270 DIR *dir;
272 path = "/dev";
273 dir = opendir(path);
274 if (dir != NULL) {
275 while ((entry = readdir(dir)) != NULL) {
276 if (_is_usbdev_entry(entry, NULL, NULL)) {
277 /* found one; that's enough */
278 ret = path;
279 usbdev_names = 1;
280 break;
283 closedir(dir);
287 if (ret != NULL)
288 usbi_dbg("found usbfs at %s", ret);
290 return ret;
293 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
294 * seem to lack it). fall back to REALTIME if we have to. */
295 static clockid_t find_monotonic_clock(void)
297 #ifdef CLOCK_MONOTONIC
298 struct timespec ts;
299 int r;
301 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
302 * because it's not available through timerfd */
303 r = clock_gettime(CLOCK_MONOTONIC, &ts);
304 if (r == 0)
305 return CLOCK_MONOTONIC;
306 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
307 #endif
309 return CLOCK_REALTIME;
312 static int kernel_version_ge(int major, int minor, int sublevel)
314 struct utsname uts;
315 int atoms, kmajor, kminor, ksublevel;
317 if (uname(&uts) < 0)
318 return -1;
319 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
320 if (atoms < 1)
321 return -1;
323 if (kmajor > major)
324 return 1;
325 if (kmajor < major)
326 return 0;
328 /* kmajor == major */
329 if (atoms < 2)
330 return 0 == minor && 0 == sublevel;
331 if (kminor > minor)
332 return 1;
333 if (kminor < minor)
334 return 0;
336 /* kminor == minor */
337 if (atoms < 3)
338 return 0 == sublevel;
340 return ksublevel >= sublevel;
343 /* Return 1 if filename exists inside dirname in sysfs.
344 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
345 static int sysfs_has_file(const char *dirname, const char *filename)
347 struct stat statbuf;
348 char path[PATH_MAX];
349 int r;
351 snprintf(path, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, dirname, filename);
352 r = stat(path, &statbuf);
353 if (r == 0 && S_ISREG(statbuf.st_mode))
354 return 1;
356 return 0;
359 static int op_init(struct libusb_context *ctx)
361 struct stat statbuf;
362 int r;
364 usbfs_path = find_usbfs_path();
365 if (!usbfs_path) {
366 usbi_err(ctx, "could not find usbfs");
367 return LIBUSB_ERROR_OTHER;
370 if (monotonic_clkid == -1)
371 monotonic_clkid = find_monotonic_clock();
373 if (supports_flag_bulk_continuation == -1) {
374 /* bulk continuation URB flag available from Linux 2.6.32 */
375 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
376 if (supports_flag_bulk_continuation == -1) {
377 usbi_err(ctx, "error checking for bulk continuation support");
378 return LIBUSB_ERROR_OTHER;
382 if (supports_flag_bulk_continuation)
383 usbi_dbg("bulk continuation flag supported");
385 if (-1 == supports_flag_zero_packet) {
386 /* zero length packet URB flag fixed since Linux 2.6.31 */
387 supports_flag_zero_packet = kernel_version_ge(2,6,31);
388 if (-1 == supports_flag_zero_packet) {
389 usbi_err(ctx, "error checking for zero length packet support");
390 return LIBUSB_ERROR_OTHER;
394 if (supports_flag_zero_packet)
395 usbi_dbg("zero length packet flag supported");
397 r = stat(SYSFS_DEVICE_PATH, &statbuf);
398 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
399 DIR *devices = opendir(SYSFS_DEVICE_PATH);
400 struct dirent *entry;
402 usbi_dbg("found usb devices in sysfs");
404 if (!devices) {
405 usbi_err(ctx, "opendir devices failed errno=%d", errno);
406 return LIBUSB_ERROR_IO;
409 /* Make sure sysfs supports all the required files. If it
410 * does not, then usbfs will be used instead. Determine
411 * this by looping through the directories in
412 * SYSFS_DEVICE_PATH. With the assumption that there will
413 * always be subdirectories of the name usbN (usb1, usb2,
414 * etc) representing the root hubs, check the usbN
415 * subdirectories to see if they have all the needed files.
416 * This algorithm uses the usbN subdirectories (root hubs)
417 * because a device disconnection will cause a race
418 * condition regarding which files are available, sometimes
419 * causing an incorrect result. The root hubs are used
420 * because it is assumed that they will always be present.
421 * See the "sysfs vs usbfs" comment at the top of this file
422 * for more details. */
423 while ((entry = readdir(devices))) {
424 int has_busnum=0, has_devnum=0, has_descriptors=0;
425 int has_configuration_value=0;
427 /* Only check the usbN directories. */
428 if (strncmp(entry->d_name, "usb", 3) != 0)
429 continue;
431 /* Check for the files libusbx needs from sysfs. */
432 has_busnum = sysfs_has_file(entry->d_name, "busnum");
433 has_devnum = sysfs_has_file(entry->d_name, "devnum");
434 has_descriptors = sysfs_has_file(entry->d_name, "descriptors");
435 has_configuration_value = sysfs_has_file(entry->d_name, "bConfigurationValue");
437 if (has_busnum && has_devnum && has_configuration_value)
438 sysfs_can_relate_devices = 1;
439 if (has_descriptors)
440 sysfs_has_descriptors = 1;
442 /* Only need to check until we've found ONE device which
443 has all the attributes. */
444 if (sysfs_has_descriptors && sysfs_can_relate_devices)
445 break;
447 closedir(devices);
449 /* Only use sysfs descriptors if the rest of
450 sysfs will work for libusb. */
451 if (!sysfs_can_relate_devices)
452 sysfs_has_descriptors = 0;
453 } else {
454 usbi_dbg("sysfs usb info not available");
455 sysfs_has_descriptors = 0;
456 sysfs_can_relate_devices = 0;
459 usbi_mutex_static_lock(&hotplug_lock);
460 r = LIBUSB_SUCCESS;
461 if (init_count == 0) {
462 /* start up hotplug event handler */
463 r = linux_start_event_monitor();
465 if (r == LIBUSB_SUCCESS) {
466 r = linux_scan_devices(ctx);
467 if (r == LIBUSB_SUCCESS)
468 init_count++;
469 else
470 linux_stop_event_monitor();
471 } else
472 usbi_err(ctx, "error starting hotplug event monitor");
473 usbi_mutex_static_unlock(&hotplug_lock);
475 return r;
478 static void op_exit(void)
480 usbi_mutex_static_lock(&hotplug_lock);
481 assert(init_count != 0);
482 if (!--init_count) {
483 /* tear down event handler */
484 (void)linux_stop_event_monitor();
486 usbi_mutex_static_unlock(&hotplug_lock);
489 static int linux_start_event_monitor(void)
491 #if defined(USE_UDEV)
492 return linux_udev_start_event_monitor();
493 #else
494 return linux_netlink_start_event_monitor();
495 #endif
498 static int linux_stop_event_monitor(void)
500 #if defined(USE_UDEV)
501 return linux_udev_stop_event_monitor();
502 #else
503 return linux_netlink_stop_event_monitor();
504 #endif
507 static int linux_scan_devices(struct libusb_context *ctx)
509 #if defined(USE_UDEV)
510 return linux_udev_scan_devices(ctx);
511 #else
512 return linux_default_scan_devices(ctx);
513 #endif
516 static int usbfs_get_device_descriptor(struct libusb_device *dev,
517 unsigned char *buffer)
519 struct linux_device_priv *priv = _device_priv(dev);
521 /* return cached copy */
522 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
523 return 0;
526 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
528 struct linux_device_priv *priv = _device_priv(dev);
529 char filename[PATH_MAX];
530 int fd;
532 snprintf(filename, PATH_MAX, "%s/%s/%s",
533 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
534 fd = open(filename, O_RDONLY);
535 if (fd < 0) {
536 usbi_err(DEVICE_CTX(dev),
537 "open %s failed ret=%d errno=%d", filename, fd, errno);
538 return LIBUSB_ERROR_IO;
541 return fd;
544 /* Note only suitable for attributes which always read >= 0, < 0 is error */
545 static int __read_sysfs_attr(struct libusb_context *ctx,
546 const char *devname, const char *attr)
548 char filename[PATH_MAX];
549 FILE *f;
550 int r, value;
552 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
553 devname, attr);
554 f = fopen(filename, "r");
555 if (f == NULL) {
556 if (errno == ENOENT) {
557 /* File doesn't exist. Assume the device has been
558 disconnected (see trac ticket #70). */
559 return LIBUSB_ERROR_NO_DEVICE;
561 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
562 return LIBUSB_ERROR_IO;
565 r = fscanf(f, "%d", &value);
566 fclose(f);
567 if (r != 1) {
568 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
569 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
571 if (value < 0) {
572 usbi_err(ctx, "%s contains a negative value", filename);
573 return LIBUSB_ERROR_IO;
576 return value;
579 static int sysfs_get_device_descriptor(struct libusb_device *dev,
580 unsigned char *buffer)
582 int fd;
583 ssize_t r;
585 /* sysfs provides access to an in-memory copy of the device descriptor,
586 * so we use that rather than keeping our own copy */
588 fd = _open_sysfs_attr(dev, "descriptors");
589 if (fd < 0)
590 return fd;
592 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
593 close(fd);
594 if (r < 0) {
595 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
596 return LIBUSB_ERROR_IO;
597 } else if (r < DEVICE_DESC_LENGTH) {
598 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
599 return LIBUSB_ERROR_IO;
602 return 0;
605 static int op_get_device_descriptor(struct libusb_device *dev,
606 unsigned char *buffer, int *host_endian)
608 if (sysfs_has_descriptors) {
609 *host_endian = 0;
610 return sysfs_get_device_descriptor(dev, buffer);
611 } else {
612 *host_endian = 1; /* usbfs converts the device desc to host */
613 return usbfs_get_device_descriptor(dev, buffer);
617 static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
618 unsigned char *buffer, size_t len)
620 struct linux_device_priv *priv = _device_priv(dev);
621 if (!priv->config_descriptor)
622 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
624 /* retrieve cached copy */
625 memcpy(buffer, priv->config_descriptor, len);
626 return 0;
629 /* read the bConfigurationValue for a device */
630 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
632 char *endptr;
633 char tmp[4] = {0, 0, 0, 0};
634 long num;
635 int fd;
636 ssize_t r;
638 fd = _open_sysfs_attr(dev, "bConfigurationValue");
639 if (fd < 0)
640 return fd;
642 r = read(fd, tmp, sizeof(tmp));
643 close(fd);
644 if (r < 0) {
645 usbi_err(DEVICE_CTX(dev),
646 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
647 return LIBUSB_ERROR_IO;
648 } else if (r == 0) {
649 usbi_dbg("device unconfigured");
650 *config = -1;
651 return 0;
654 if (tmp[sizeof(tmp) - 1] != 0) {
655 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
656 return LIBUSB_ERROR_IO;
657 } else if (tmp[0] == 0) {
658 usbi_err(DEVICE_CTX(dev), "no configuration value?");
659 return LIBUSB_ERROR_IO;
662 num = strtol(tmp, &endptr, 10);
663 if (endptr == tmp) {
664 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
665 return LIBUSB_ERROR_IO;
668 *config = (int) num;
669 return 0;
672 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
673 * seeks to the next one. */
674 static int seek_to_next_config(struct libusb_context *ctx, int fd)
676 struct libusb_config_descriptor config;
677 unsigned char tmp[6];
678 off_t off;
679 ssize_t r;
681 /* read first 6 bytes of descriptor */
682 r = read(fd, tmp, sizeof(tmp));
683 if (r < 0) {
684 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
685 return LIBUSB_ERROR_IO;
686 } else if (r < sizeof(tmp)) {
687 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
688 return LIBUSB_ERROR_IO;
691 /* seek forward to end of config */
692 usbi_parse_descriptor(tmp, "bbwbb", &config, 0);
693 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
694 if (off < 0) {
695 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
696 return LIBUSB_ERROR_IO;
699 return 0;
702 static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
703 unsigned char *buffer, size_t len)
705 int fd;
706 ssize_t r;
707 off_t off;
708 int to_copy;
709 int config;
710 unsigned char tmp[6];
712 r = sysfs_get_active_config(dev, &config);
713 if (r < 0)
714 return r;
715 if (config == -1)
716 return LIBUSB_ERROR_NOT_FOUND;
718 usbi_dbg("active configuration %d", config);
720 /* sysfs provides access to an in-memory copy of the device descriptor,
721 * so we use that rather than keeping our own copy */
723 fd = _open_sysfs_attr(dev, "descriptors");
724 if (fd < 0)
725 return fd;
727 /* device might have been unconfigured since we read bConfigurationValue,
728 * so first check that there is any config descriptor data at all... */
729 off = lseek(fd, 0, SEEK_END);
730 if (off < 1) {
731 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
732 off, errno);
733 close(fd);
734 return LIBUSB_ERROR_IO;
735 } else if (off == DEVICE_DESC_LENGTH) {
736 close(fd);
737 return LIBUSB_ERROR_NOT_FOUND;
740 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
741 if (off < 0) {
742 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
743 close(fd);
744 return LIBUSB_ERROR_IO;
747 /* unbounded loop: we expect the descriptor to be present under all
748 * circumstances */
749 while (1) {
750 r = read(fd, tmp, sizeof(tmp));
751 if (r < 0) {
752 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
753 fd, errno);
754 return LIBUSB_ERROR_IO;
755 } else if (r < sizeof(tmp)) {
756 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
757 return LIBUSB_ERROR_IO;
760 /* check bConfigurationValue */
761 if (tmp[5] == config)
762 break;
764 /* try the next descriptor */
765 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
766 if (off < 0)
767 return LIBUSB_ERROR_IO;
769 r = seek_to_next_config(DEVICE_CTX(dev), fd);
770 if (r < 0)
771 return r;
774 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
775 memcpy(buffer, tmp, to_copy);
776 if (len > sizeof(tmp)) {
777 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
778 if (r < 0) {
779 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
780 fd, errno);
781 r = LIBUSB_ERROR_IO;
782 } else if (r == 0) {
783 usbi_dbg("device is unconfigured");
784 r = LIBUSB_ERROR_NOT_FOUND;
785 } else if (r < len - sizeof(tmp)) {
786 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
787 r = 0;
789 } else {
790 r = 0;
793 close(fd);
794 return r;
797 int linux_get_device_address (struct libusb_context *ctx, int detached,
798 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
799 const char *sys_name)
801 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
802 /* can't use sysfs to read the bus and device number if the
803 * device has been detached */
804 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
805 if (NULL == dev_node) {
806 return LIBUSB_ERROR_OTHER;
809 /* will this work with all supported kernel versions? */
810 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
811 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
812 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
813 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
816 return LIBUSB_SUCCESS;
819 usbi_dbg("scan %s", sys_name);
821 *busnum = __read_sysfs_attr(ctx, sys_name, "busnum");
822 if (0 > *busnum)
823 return *busnum;
825 *devaddr = __read_sysfs_attr(ctx, sys_name, "devnum");
826 if (0 > *devaddr)
827 return *devaddr;
829 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
830 if (*busnum > 255 || *devaddr > 255)
831 return LIBUSB_ERROR_INVALID_PARAM;
833 return LIBUSB_SUCCESS;
836 static int op_get_active_config_descriptor(struct libusb_device *dev,
837 unsigned char *buffer, size_t len, int *host_endian)
839 /* Unlike the device desc. config descs. are always in raw format */
840 *host_endian = 0;
841 if (sysfs_has_descriptors) {
842 return sysfs_get_active_config_descriptor(dev, buffer, len);
843 } else {
844 return usbfs_get_active_config_descriptor(dev, buffer, len);
848 /* takes a usbfs fd, attempts to find the requested config and copy a certain
849 * amount of it into an output buffer. */
850 static int get_config_descriptor(struct libusb_context *ctx, int fd,
851 uint8_t config_index, unsigned char *buffer, size_t len)
853 off_t off;
854 ssize_t r;
856 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
857 if (off < 0) {
858 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
859 return LIBUSB_ERROR_IO;
862 /* might need to skip some configuration descriptors to reach the
863 * requested configuration */
864 while (config_index > 0) {
865 r = seek_to_next_config(ctx, fd);
866 if (r < 0)
867 return r;
868 config_index--;
871 /* read the rest of the descriptor */
872 r = read(fd, buffer, len);
873 if (r < 0) {
874 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
875 return LIBUSB_ERROR_IO;
876 } else if (r < len) {
877 usbi_err(ctx, "short output read %d/%d", r, len);
880 return 0;
883 static int op_get_config_descriptor(struct libusb_device *dev,
884 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
886 int fd;
887 int r;
889 /* Unlike the device desc. config descs. are always in raw format */
890 *host_endian = 0;
892 /* always read from usbfs: sysfs only has the active descriptor
893 * this will involve waking the device up, but oh well! */
895 /* FIXME: the above is no longer true, new kernels have all descriptors
896 * in the descriptors file. but its kinda hard to detect if the kernel
897 * is sufficiently new. */
899 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
900 if (fd < 0)
901 return fd;
903 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
904 close(fd);
905 return r;
908 /* cache the active config descriptor in memory. a value of -1 means that
909 * we aren't sure which one is active, so just assume the first one.
910 * only for usbfs. */
911 static int cache_active_config(struct libusb_device *dev, int fd,
912 int active_config)
914 struct linux_device_priv *priv = _device_priv(dev);
915 struct libusb_config_descriptor config;
916 unsigned char tmp[8];
917 unsigned char *buf;
918 int idx;
919 int r;
921 if (active_config == -1) {
922 idx = 0;
923 } else {
924 r = usbi_get_config_index_by_value(dev, active_config, &idx);
925 if (r < 0)
926 return r;
927 if (idx == -1)
928 return LIBUSB_ERROR_NOT_FOUND;
931 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
932 if (r < 0) {
933 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
934 return r;
937 usbi_parse_descriptor(tmp, "bbw", &config, 0);
938 buf = malloc(config.wTotalLength);
939 if (!buf)
940 return LIBUSB_ERROR_NO_MEM;
942 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
943 config.wTotalLength);
944 if (r < 0) {
945 free(buf);
946 return r;
949 if (priv->config_descriptor)
950 free(priv->config_descriptor);
951 priv->config_descriptor = buf;
952 return 0;
955 /* send a control message to retrieve active configuration */
956 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
958 unsigned char active_config = 0;
959 int r;
961 struct usbfs_ctrltransfer ctrl = {
962 .bmRequestType = LIBUSB_ENDPOINT_IN,
963 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
964 .wValue = 0,
965 .wIndex = 0,
966 .wLength = 1,
967 .timeout = 1000,
968 .data = &active_config
971 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
972 if (r < 0) {
973 if (errno == ENODEV)
974 return LIBUSB_ERROR_NO_DEVICE;
976 /* we hit this error path frequently with buggy devices :( */
977 usbi_warn(DEVICE_CTX(dev),
978 "get_configuration failed ret=%d errno=%d", r, errno);
979 return LIBUSB_ERROR_IO;
982 return active_config;
985 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
986 uint8_t devaddr, const char *sysfs_dir)
988 struct linux_device_priv *priv = _device_priv(dev);
989 unsigned char *dev_buf;
990 char path[PATH_MAX];
991 int fd, speed;
992 int active_config = 0;
993 int device_configured = 1;
994 ssize_t r;
996 dev->bus_number = busnum;
997 dev->device_address = devaddr;
999 if (sysfs_dir) {
1000 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
1001 if (!priv->sysfs_dir)
1002 return LIBUSB_ERROR_NO_MEM;
1003 strcpy(priv->sysfs_dir, sysfs_dir);
1005 /* Note speed can contain 1.5, in this case __read_sysfs_attr
1006 will stop parsing at the '.' and return 1 */
1007 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
1008 if (speed >= 0) {
1009 switch (speed) {
1010 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
1011 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
1012 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
1013 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
1014 default:
1015 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
1020 if (sysfs_has_descriptors)
1021 return 0;
1023 /* cache device descriptor in memory so that we can retrieve it later
1024 * without waking the device up (op_get_device_descriptor) */
1026 priv->dev_descriptor = NULL;
1027 priv->config_descriptor = NULL;
1029 if (sysfs_can_relate_devices) {
1030 int tmp = sysfs_get_active_config(dev, &active_config);
1031 if (tmp < 0)
1032 return tmp;
1033 if (active_config == -1)
1034 device_configured = 0;
1037 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1038 if (fd == LIBUSB_ERROR_ACCESS) {
1039 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1040 /* if we only have read-only access to the device, we cannot
1041 * send a control message to determine the active config. just
1042 * assume the first one is active. */
1043 active_config = -1;
1046 if (fd < 0) {
1047 return LIBUSB_ERROR_IO;
1050 if (!sysfs_can_relate_devices) {
1051 if (active_config == -1) {
1052 /* if we only have read-only access to the device, we cannot
1053 * send a control message to determine the active config. just
1054 * assume the first one is active. */
1055 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
1056 "determine active configuration descriptor", path);
1057 } else {
1058 active_config = usbfs_get_active_config(dev, fd);
1059 if (active_config == LIBUSB_ERROR_IO) {
1060 /* buggy devices sometimes fail to report their active config.
1061 * assume unconfigured and continue the probing */
1062 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
1063 "configuration, assumung unconfigured");
1064 device_configured = 0;
1065 } else if (active_config < 0) {
1066 close(fd);
1067 return active_config;
1068 } else if (active_config == 0) {
1069 /* some buggy devices have a configuration 0, but we're
1070 * reaching into the corner of a corner case here, so let's
1071 * not support buggy devices in these circumstances.
1072 * stick to the specs: a configuration value of 0 means
1073 * unconfigured. */
1074 usbi_dbg("active cfg 0? assuming unconfigured device");
1075 device_configured = 0;
1080 dev_buf = malloc(DEVICE_DESC_LENGTH);
1081 if (!dev_buf) {
1082 close(fd);
1083 return LIBUSB_ERROR_NO_MEM;
1086 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
1087 if (r < 0) {
1088 usbi_err(DEVICE_CTX(dev),
1089 "read descriptor failed ret=%d errno=%d", fd, errno);
1090 free(dev_buf);
1091 close(fd);
1092 return LIBUSB_ERROR_IO;
1093 } else if (r < DEVICE_DESC_LENGTH) {
1094 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
1095 free(dev_buf);
1096 close(fd);
1097 return LIBUSB_ERROR_IO;
1100 /* bit of a hack: set num_configurations now because cache_active_config()
1101 * calls usbi_get_config_index_by_value() which uses it */
1102 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
1104 if (device_configured) {
1105 r = cache_active_config(dev, fd, active_config);
1106 if (r < 0) {
1107 close(fd);
1108 free(dev_buf);
1109 return r;
1113 close(fd);
1114 priv->dev_descriptor = dev_buf;
1115 return 0;
1118 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1120 struct libusb_context *ctx = DEVICE_CTX(dev);
1121 struct libusb_device *it;
1122 char *parent_sysfs_dir, *tmp;
1123 int ret, add_parent = 1;
1125 /* XXX -- can we figure out the topology when using usbfs? */
1126 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1127 /* either using usbfs or finding the parent of a root hub */
1128 return LIBUSB_SUCCESS;
1131 parent_sysfs_dir = strdup(sysfs_dir);
1132 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1133 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1134 dev->port_number = atoi(tmp + 1);
1135 *tmp = '\0';
1136 } else {
1137 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1138 parent_sysfs_dir);
1139 free (parent_sysfs_dir);
1140 return LIBUSB_SUCCESS;
1143 /* is the parent a root hub? */
1144 if (NULL == strchr(parent_sysfs_dir, '-')) {
1145 tmp = parent_sysfs_dir;
1146 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1147 free (tmp);
1148 if (0 > ret) {
1149 return LIBUSB_ERROR_NO_MEM;
1153 retry:
1154 /* find the parent in the context */
1155 usbi_mutex_lock(&ctx->usb_devs_lock);
1156 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1157 struct linux_device_priv *priv = _device_priv(it);
1158 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1159 dev->parent_dev = libusb_ref_device(it);
1160 break;
1163 usbi_mutex_unlock(&ctx->usb_devs_lock);
1165 if (!dev->parent_dev && add_parent) {
1166 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1167 parent_sysfs_dir);
1168 sysfs_scan_device(ctx, parent_sysfs_dir);
1169 add_parent = 0;
1170 goto retry;
1173 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1174 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1176 free (parent_sysfs_dir);
1178 return LIBUSB_SUCCESS;
1181 int linux_enumerate_device(struct libusb_context *ctx,
1182 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1184 unsigned long session_id;
1185 struct libusb_device *dev;
1186 int r = 0;
1188 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1189 * will be reused. instead we should add a simple sysfs attribute with
1190 * a session ID. */
1191 session_id = busnum << 8 | devaddr;
1192 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1193 session_id);
1195 if (usbi_get_device_by_session_id(ctx, session_id)) {
1196 /* device already exists in the context */
1197 usbi_dbg("session_id %ld already exists", session_id);
1198 return LIBUSB_SUCCESS;
1201 usbi_dbg("allocating new device for %d/%d (session %ld)",
1202 busnum, devaddr, session_id);
1203 dev = usbi_alloc_device(ctx, session_id);
1204 if (!dev)
1205 return LIBUSB_ERROR_NO_MEM;
1207 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1208 if (r < 0)
1209 goto out;
1210 r = usbi_sanitize_device(dev);
1211 if (r < 0)
1212 goto out;
1214 r = linux_get_parent_info(dev, sysfs_dir);
1215 if (r < 0)
1216 goto out;
1217 out:
1218 if (r < 0)
1219 libusb_unref_device(dev);
1220 else
1221 usbi_connect_device(dev);
1223 return r;
1226 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1228 struct libusb_context *ctx;
1230 usbi_mutex_static_lock(&active_contexts_lock);
1231 usbi_mutex_static_lock(&hotplug_lock);
1232 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1233 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1235 usbi_mutex_static_unlock(&hotplug_lock);
1236 usbi_mutex_static_unlock(&active_contexts_lock);
1239 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1241 struct libusb_context *ctx;
1242 struct libusb_device *dev;
1243 unsigned long session_id = busnum << 8 | devaddr;
1245 usbi_mutex_static_lock(&active_contexts_lock);
1246 usbi_mutex_static_lock(&hotplug_lock);
1247 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1248 dev = usbi_get_device_by_session_id (ctx, session_id);
1249 if (NULL != dev) {
1250 usbi_disconnect_device (dev);
1251 } else {
1252 usbi_dbg("device not found for session %x", session_id);
1255 usbi_mutex_static_unlock(&hotplug_lock);
1256 usbi_mutex_static_unlock(&active_contexts_lock);
1259 #if !defined(USE_UDEV)
1260 /* open a bus directory and adds all discovered devices to the context */
1261 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1263 DIR *dir;
1264 char dirpath[PATH_MAX];
1265 struct dirent *entry;
1266 int r = LIBUSB_ERROR_IO;
1268 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1269 usbi_dbg("%s", dirpath);
1270 dir = opendir(dirpath);
1271 if (!dir) {
1272 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1273 /* FIXME: should handle valid race conditions like hub unplugged
1274 * during directory iteration - this is not an error */
1275 return r;
1278 while ((entry = readdir(dir))) {
1279 int devaddr;
1281 if (entry->d_name[0] == '.')
1282 continue;
1284 devaddr = atoi(entry->d_name);
1285 if (devaddr == 0) {
1286 usbi_dbg("unknown dir entry %s", entry->d_name);
1287 continue;
1290 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1291 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1292 continue;
1295 r = 0;
1298 closedir(dir);
1299 return r;
1302 static int usbfs_get_device_list(struct libusb_context *ctx)
1304 struct dirent *entry;
1305 DIR *buses = opendir(usbfs_path);
1306 int r = 0;
1308 if (!buses) {
1309 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1310 return LIBUSB_ERROR_IO;
1313 while ((entry = readdir(buses))) {
1314 int busnum;
1316 if (entry->d_name[0] == '.')
1317 continue;
1319 if (usbdev_names) {
1320 int devaddr;
1321 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1322 continue;
1324 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1325 if (r < 0) {
1326 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1327 continue;
1329 } else {
1330 busnum = atoi(entry->d_name);
1331 if (busnum == 0) {
1332 usbi_dbg("unknown dir entry %s", entry->d_name);
1333 continue;
1336 r = usbfs_scan_busdir(ctx, busnum);
1337 if (r < 0)
1338 break;
1342 closedir(buses);
1343 return r;
1346 #endif
1348 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1350 uint8_t busnum, devaddr;
1351 int ret;
1353 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1354 if (LIBUSB_SUCCESS != ret) {
1355 return ret;
1358 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1359 devname);
1362 #if !defined(USE_UDEV)
1363 static int sysfs_get_device_list(struct libusb_context *ctx)
1365 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1366 struct dirent *entry;
1367 int r = LIBUSB_ERROR_IO;
1369 if (!devices) {
1370 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1371 return r;
1374 while ((entry = readdir(devices))) {
1375 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1376 || strchr(entry->d_name, ':'))
1377 continue;
1379 if (sysfs_scan_device(ctx, entry->d_name)) {
1380 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1381 continue;
1384 r = 0;
1387 closedir(devices);
1388 return r;
1391 static int linux_default_scan_devices (struct libusb_context *ctx)
1393 /* we can retrieve device list and descriptors from sysfs or usbfs.
1394 * sysfs is preferable, because if we use usbfs we end up resuming
1395 * any autosuspended USB devices. however, sysfs is not available
1396 * everywhere, so we need a usbfs fallback too.
1398 * as described in the "sysfs vs usbfs" comment at the top of this
1399 * file, sometimes we have sysfs but not enough information to
1400 * relate sysfs devices to usbfs nodes. op_init() determines the
1401 * adequacy of sysfs and sets sysfs_can_relate_devices.
1403 if (sysfs_can_relate_devices != 0)
1404 return sysfs_get_device_list(ctx);
1405 else
1406 return usbfs_get_device_list(ctx);
1408 #endif
1410 static int op_open(struct libusb_device_handle *handle)
1412 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1413 int r;
1415 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1416 if (hpriv->fd < 0)
1417 return hpriv->fd;
1419 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1420 if (r < 0) {
1421 if (errno == ENOTTY)
1422 usbi_dbg("getcap not available");
1423 else
1424 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1425 hpriv->caps = 0;
1426 if (supports_flag_zero_packet)
1427 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1428 if (supports_flag_bulk_continuation)
1429 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1432 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1435 static void op_close(struct libusb_device_handle *dev_handle)
1437 int fd = _device_handle_priv(dev_handle)->fd;
1438 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1439 close(fd);
1442 static int op_get_configuration(struct libusb_device_handle *handle,
1443 int *config)
1445 int r;
1446 if (sysfs_can_relate_devices != 1)
1447 return LIBUSB_ERROR_NOT_SUPPORTED;
1449 r = sysfs_get_active_config(handle->dev, config);
1450 if (r < 0)
1451 return r;
1453 if (*config == -1) {
1454 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1455 *config = 0;
1458 return 0;
1461 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1463 struct linux_device_priv *priv = _device_priv(handle->dev);
1464 int fd = _device_handle_priv(handle)->fd;
1465 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1466 if (r) {
1467 if (errno == EINVAL)
1468 return LIBUSB_ERROR_NOT_FOUND;
1469 else if (errno == EBUSY)
1470 return LIBUSB_ERROR_BUSY;
1471 else if (errno == ENODEV)
1472 return LIBUSB_ERROR_NO_DEVICE;
1474 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1475 return LIBUSB_ERROR_OTHER;
1478 if (!sysfs_has_descriptors) {
1479 /* update our cached active config descriptor */
1480 if (config == -1) {
1481 if (priv->config_descriptor) {
1482 free(priv->config_descriptor);
1483 priv->config_descriptor = NULL;
1485 } else {
1486 r = cache_active_config(handle->dev, fd, config);
1487 if (r < 0)
1488 usbi_warn(HANDLE_CTX(handle),
1489 "failed to update cached config descriptor, error %d", r);
1493 return 0;
1496 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1498 int fd = _device_handle_priv(handle)->fd;
1499 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1500 if (r) {
1501 if (errno == ENOENT)
1502 return LIBUSB_ERROR_NOT_FOUND;
1503 else if (errno == EBUSY)
1504 return LIBUSB_ERROR_BUSY;
1505 else if (errno == ENODEV)
1506 return LIBUSB_ERROR_NO_DEVICE;
1508 usbi_err(HANDLE_CTX(handle),
1509 "claim interface failed, error %d errno %d", r, errno);
1510 return LIBUSB_ERROR_OTHER;
1512 return 0;
1515 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1517 int fd = _device_handle_priv(handle)->fd;
1518 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1519 if (r) {
1520 if (errno == ENODEV)
1521 return LIBUSB_ERROR_NO_DEVICE;
1523 usbi_err(HANDLE_CTX(handle),
1524 "release interface failed, error %d errno %d", r, errno);
1525 return LIBUSB_ERROR_OTHER;
1527 return 0;
1530 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1531 int altsetting)
1533 int fd = _device_handle_priv(handle)->fd;
1534 struct usbfs_setinterface setintf;
1535 int r;
1537 setintf.interface = iface;
1538 setintf.altsetting = altsetting;
1539 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1540 if (r) {
1541 if (errno == EINVAL)
1542 return LIBUSB_ERROR_NOT_FOUND;
1543 else if (errno == ENODEV)
1544 return LIBUSB_ERROR_NO_DEVICE;
1546 usbi_err(HANDLE_CTX(handle),
1547 "setintf failed error %d errno %d", r, errno);
1548 return LIBUSB_ERROR_OTHER;
1551 return 0;
1554 static int op_clear_halt(struct libusb_device_handle *handle,
1555 unsigned char endpoint)
1557 int fd = _device_handle_priv(handle)->fd;
1558 unsigned int _endpoint = endpoint;
1559 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1560 if (r) {
1561 if (errno == ENOENT)
1562 return LIBUSB_ERROR_NOT_FOUND;
1563 else if (errno == ENODEV)
1564 return LIBUSB_ERROR_NO_DEVICE;
1566 usbi_err(HANDLE_CTX(handle),
1567 "clear_halt failed error %d errno %d", r, errno);
1568 return LIBUSB_ERROR_OTHER;
1571 return 0;
1574 static int op_reset_device(struct libusb_device_handle *handle)
1576 int fd = _device_handle_priv(handle)->fd;
1577 int i, r, ret = 0;
1579 /* Doing a device reset will cause the usbfs driver to get unbound
1580 from any interfaces it is bound to. By voluntarily unbinding
1581 the usbfs driver ourself, we stop the kernel from rebinding
1582 the interface after reset (which would end up with the interface
1583 getting bound to the in kernel driver if any). */
1584 for (i = 0; i < USB_MAXINTERFACES; i++) {
1585 if (handle->claimed_interfaces & (1L << i)) {
1586 op_release_interface(handle, i);
1590 usbi_mutex_lock(&handle->lock);
1591 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1592 if (r) {
1593 if (errno == ENODEV) {
1594 ret = LIBUSB_ERROR_NOT_FOUND;
1595 goto out;
1598 usbi_err(HANDLE_CTX(handle),
1599 "reset failed error %d errno %d", r, errno);
1600 ret = LIBUSB_ERROR_OTHER;
1601 goto out;
1604 /* And re-claim any interfaces which were claimed before the reset */
1605 for (i = 0; i < USB_MAXINTERFACES; i++) {
1606 if (handle->claimed_interfaces & (1L << i)) {
1607 r = op_claim_interface(handle, i);
1608 if (r) {
1609 usbi_warn(HANDLE_CTX(handle),
1610 "failed to re-claim interface %d after reset", i);
1611 handle->claimed_interfaces &= ~(1L << i);
1615 out:
1616 usbi_mutex_unlock(&handle->lock);
1617 return ret;
1620 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1621 int interface)
1623 int fd = _device_handle_priv(handle)->fd;
1624 struct usbfs_getdriver getdrv;
1625 int r;
1627 getdrv.interface = interface;
1628 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1629 if (r) {
1630 if (errno == ENODATA)
1631 return 0;
1632 else if (errno == ENODEV)
1633 return LIBUSB_ERROR_NO_DEVICE;
1635 usbi_err(HANDLE_CTX(handle),
1636 "get driver failed error %d errno %d", r, errno);
1637 return LIBUSB_ERROR_OTHER;
1640 return 1;
1643 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1644 int interface)
1646 int fd = _device_handle_priv(handle)->fd;
1647 struct usbfs_ioctl command;
1648 struct usbfs_getdriver getdrv;
1649 int r;
1651 command.ifno = interface;
1652 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1653 command.data = NULL;
1655 getdrv.interface = interface;
1656 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1657 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1658 return LIBUSB_ERROR_NOT_FOUND;
1660 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1661 if (r) {
1662 if (errno == ENODATA)
1663 return LIBUSB_ERROR_NOT_FOUND;
1664 else if (errno == EINVAL)
1665 return LIBUSB_ERROR_INVALID_PARAM;
1666 else if (errno == ENODEV)
1667 return LIBUSB_ERROR_NO_DEVICE;
1669 usbi_err(HANDLE_CTX(handle),
1670 "detach failed error %d errno %d", r, errno);
1671 return LIBUSB_ERROR_OTHER;
1674 return 0;
1677 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1678 int interface)
1680 int fd = _device_handle_priv(handle)->fd;
1681 struct usbfs_ioctl command;
1682 int r;
1684 command.ifno = interface;
1685 command.ioctl_code = IOCTL_USBFS_CONNECT;
1686 command.data = NULL;
1688 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1689 if (r < 0) {
1690 if (errno == ENODATA)
1691 return LIBUSB_ERROR_NOT_FOUND;
1692 else if (errno == EINVAL)
1693 return LIBUSB_ERROR_INVALID_PARAM;
1694 else if (errno == ENODEV)
1695 return LIBUSB_ERROR_NO_DEVICE;
1696 else if (errno == EBUSY)
1697 return LIBUSB_ERROR_BUSY;
1699 usbi_err(HANDLE_CTX(handle),
1700 "attach failed error %d errno %d", r, errno);
1701 return LIBUSB_ERROR_OTHER;
1702 } else if (r == 0) {
1703 return LIBUSB_ERROR_NOT_FOUND;
1706 return 0;
1709 static void op_destroy_device(struct libusb_device *dev)
1711 struct linux_device_priv *priv = _device_priv(dev);
1712 if (!sysfs_has_descriptors) {
1713 if (priv->dev_descriptor)
1714 free(priv->dev_descriptor);
1715 if (priv->config_descriptor)
1716 free(priv->config_descriptor);
1718 if (priv->sysfs_dir)
1719 free(priv->sysfs_dir);
1722 /* URBs are discarded in reverse order of submission to avoid races. */
1723 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1725 struct libusb_transfer *transfer =
1726 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1727 struct linux_transfer_priv *tpriv =
1728 usbi_transfer_get_os_priv(itransfer);
1729 struct linux_device_handle_priv *dpriv =
1730 _device_handle_priv(transfer->dev_handle);
1731 int i, ret = 0;
1732 struct usbfs_urb *urb;
1734 for (i = last_plus_one - 1; i >= first; i--) {
1735 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1736 urb = tpriv->iso_urbs[i];
1737 else
1738 urb = &tpriv->urbs[i];
1740 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1741 continue;
1743 if (EINVAL == errno) {
1744 usbi_dbg("URB not found --> assuming ready to be reaped");
1745 if (i == (last_plus_one - 1))
1746 ret = LIBUSB_ERROR_NOT_FOUND;
1747 } else if (ENODEV == errno) {
1748 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1749 ret = LIBUSB_ERROR_NO_DEVICE;
1750 } else {
1751 usbi_warn(TRANSFER_CTX(transfer),
1752 "unrecognised discard errno %d", errno);
1753 ret = LIBUSB_ERROR_OTHER;
1756 return ret;
1759 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1761 int i;
1762 for (i = 0; i < tpriv->num_urbs; i++) {
1763 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1764 if (!urb)
1765 break;
1766 free(urb);
1769 free(tpriv->iso_urbs);
1770 tpriv->iso_urbs = NULL;
1773 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1774 unsigned char urb_type)
1776 struct libusb_transfer *transfer =
1777 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1778 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1779 struct linux_device_handle_priv *dpriv =
1780 _device_handle_priv(transfer->dev_handle);
1781 struct usbfs_urb *urbs;
1782 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1783 == LIBUSB_ENDPOINT_OUT;
1784 int bulk_buffer_len, use_bulk_continuation;
1785 int r;
1786 int i;
1787 size_t alloc_size;
1789 if (tpriv->urbs)
1790 return LIBUSB_ERROR_BUSY;
1792 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1793 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1794 return LIBUSB_ERROR_NOT_SUPPORTED;
1797 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1798 * around this by splitting large transfers into 16k blocks, and then
1799 * submit all urbs at once. it would be simpler to submit one urb at
1800 * a time, but there is a big performance gain doing it this way.
1802 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1803 * using arbritary large transfers can still be a bad idea though, as
1804 * the kernel needs to allocate physical contiguous memory for this,
1805 * which may fail for large buffers.
1807 * The kernel solves this problem by splitting the transfer into
1808 * blocks itself when the host-controller is scatter-gather capable
1809 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1811 * Last, there is the issue of short-transfers when splitting, for
1812 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1813 * is needed, but this is not always available.
1815 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1816 /* Good! Just submit everything in one go */
1817 bulk_buffer_len = transfer->length ? transfer->length : 1;
1818 use_bulk_continuation = 0;
1819 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1820 /* Split the transfers and use bulk-continuation to
1821 avoid issues with short-transfers */
1822 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1823 use_bulk_continuation = 1;
1824 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1825 /* Don't split, assume the kernel can alloc the buffer
1826 (otherwise the submit will fail with -ENOMEM) */
1827 bulk_buffer_len = transfer->length ? transfer->length : 1;
1828 use_bulk_continuation = 0;
1829 } else {
1830 /* Bad, splitting without bulk-continuation, short transfers
1831 which end before the last urb will not work reliable! */
1832 /* Note we don't warn here as this is "normal" on kernels <
1833 2.6.32 and not a problem for most applications */
1834 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1835 use_bulk_continuation = 0;
1838 int num_urbs = transfer->length / bulk_buffer_len;
1839 int last_urb_partial = 0;
1841 if (transfer->length == 0) {
1842 num_urbs = 1;
1843 } else if ((transfer->length % bulk_buffer_len) > 0) {
1844 last_urb_partial = 1;
1845 num_urbs++;
1847 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1848 transfer->length);
1849 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1850 urbs = calloc(1, alloc_size);
1851 if (!urbs)
1852 return LIBUSB_ERROR_NO_MEM;
1853 tpriv->urbs = urbs;
1854 tpriv->num_urbs = num_urbs;
1855 tpriv->num_retired = 0;
1856 tpriv->reap_action = NORMAL;
1857 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1859 for (i = 0; i < num_urbs; i++) {
1860 struct usbfs_urb *urb = &urbs[i];
1861 urb->usercontext = itransfer;
1862 urb->type = urb_type;
1863 urb->endpoint = transfer->endpoint;
1864 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1865 /* don't set the short not ok flag for the last URB */
1866 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1867 urb->flags = USBFS_URB_SHORT_NOT_OK;
1868 if (i == num_urbs - 1 && last_urb_partial)
1869 urb->buffer_length = transfer->length % bulk_buffer_len;
1870 else if (transfer->length == 0)
1871 urb->buffer_length = 0;
1872 else
1873 urb->buffer_length = bulk_buffer_len;
1875 if (i > 0 && use_bulk_continuation)
1876 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1878 /* we have already checked that the flag is supported */
1879 if (is_out && i == num_urbs - 1 &&
1880 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1881 urb->flags |= USBFS_URB_ZERO_PACKET;
1883 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1884 if (r < 0) {
1885 if (errno == ENODEV) {
1886 r = LIBUSB_ERROR_NO_DEVICE;
1887 } else {
1888 usbi_err(TRANSFER_CTX(transfer),
1889 "submiturb failed error %d errno=%d", r, errno);
1890 r = LIBUSB_ERROR_IO;
1893 /* if the first URB submission fails, we can simply free up and
1894 * return failure immediately. */
1895 if (i == 0) {
1896 usbi_dbg("first URB failed, easy peasy");
1897 free(urbs);
1898 tpriv->urbs = NULL;
1899 return r;
1902 /* if it's not the first URB that failed, the situation is a bit
1903 * tricky. we may need to discard all previous URBs. there are
1904 * complications:
1905 * - discarding is asynchronous - discarded urbs will be reaped
1906 * later. the user must not have freed the transfer when the
1907 * discarded URBs are reaped, otherwise libusbx will be using
1908 * freed memory.
1909 * - the earlier URBs may have completed successfully and we do
1910 * not want to throw away any data.
1911 * - this URB failing may be no error; EREMOTEIO means that
1912 * this transfer simply didn't need all the URBs we submitted
1913 * so, we report that the transfer was submitted successfully and
1914 * in case of error we discard all previous URBs. later when
1915 * the final reap completes we can report error to the user,
1916 * or success if an earlier URB was completed successfully.
1918 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1920 /* The URBs we haven't submitted yet we count as already
1921 * retired. */
1922 tpriv->num_retired += num_urbs - i;
1924 /* If we completed short then don't try to discard. */
1925 if (COMPLETED_EARLY == tpriv->reap_action)
1926 return 0;
1928 discard_urbs(itransfer, 0, i);
1930 usbi_dbg("reporting successful submission but waiting for %d "
1931 "discards before reporting error", i);
1932 return 0;
1936 return 0;
1939 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1941 struct libusb_transfer *transfer =
1942 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1943 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1944 struct linux_device_handle_priv *dpriv =
1945 _device_handle_priv(transfer->dev_handle);
1946 struct usbfs_urb **urbs;
1947 size_t alloc_size;
1948 int num_packets = transfer->num_iso_packets;
1949 int i;
1950 int this_urb_len = 0;
1951 int num_urbs = 1;
1952 int packet_offset = 0;
1953 unsigned int packet_len;
1954 unsigned char *urb_buffer = transfer->buffer;
1956 if (tpriv->iso_urbs)
1957 return LIBUSB_ERROR_BUSY;
1959 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1960 * into smaller units to meet such restriction, then fire off all the
1961 * units at once. it would be simpler if we just fired one unit at a time,
1962 * but there is a big performance gain through doing it this way.
1964 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1965 * using arbritary large transfers is still be a bad idea though, as
1966 * the kernel needs to allocate physical contiguous memory for this,
1967 * which may fail for large buffers.
1970 /* calculate how many URBs we need */
1971 for (i = 0; i < num_packets; i++) {
1972 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1973 packet_len = transfer->iso_packet_desc[i].length;
1975 if (packet_len > space_remaining) {
1976 num_urbs++;
1977 this_urb_len = packet_len;
1978 } else {
1979 this_urb_len += packet_len;
1982 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1984 alloc_size = num_urbs * sizeof(*urbs);
1985 urbs = calloc(1, alloc_size);
1986 if (!urbs)
1987 return LIBUSB_ERROR_NO_MEM;
1989 tpriv->iso_urbs = urbs;
1990 tpriv->num_urbs = num_urbs;
1991 tpriv->num_retired = 0;
1992 tpriv->reap_action = NORMAL;
1993 tpriv->iso_packet_offset = 0;
1995 /* allocate + initialize each URB with the correct number of packets */
1996 for (i = 0; i < num_urbs; i++) {
1997 struct usbfs_urb *urb;
1998 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1999 int urb_packet_offset = 0;
2000 unsigned char *urb_buffer_orig = urb_buffer;
2001 int j;
2002 int k;
2004 /* swallow up all the packets we can fit into this URB */
2005 while (packet_offset < transfer->num_iso_packets) {
2006 packet_len = transfer->iso_packet_desc[packet_offset].length;
2007 if (packet_len <= space_remaining_in_urb) {
2008 /* throw it in */
2009 urb_packet_offset++;
2010 packet_offset++;
2011 space_remaining_in_urb -= packet_len;
2012 urb_buffer += packet_len;
2013 } else {
2014 /* it can't fit, save it for the next URB */
2015 break;
2019 alloc_size = sizeof(*urb)
2020 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2021 urb = calloc(1, alloc_size);
2022 if (!urb) {
2023 free_iso_urbs(tpriv);
2024 return LIBUSB_ERROR_NO_MEM;
2026 urbs[i] = urb;
2028 /* populate packet lengths */
2029 for (j = 0, k = packet_offset - urb_packet_offset;
2030 k < packet_offset; k++, j++) {
2031 packet_len = transfer->iso_packet_desc[k].length;
2032 urb->iso_frame_desc[j].length = packet_len;
2035 urb->usercontext = itransfer;
2036 urb->type = USBFS_URB_TYPE_ISO;
2037 /* FIXME: interface for non-ASAP data? */
2038 urb->flags = USBFS_URB_ISO_ASAP;
2039 urb->endpoint = transfer->endpoint;
2040 urb->number_of_packets = urb_packet_offset;
2041 urb->buffer = urb_buffer_orig;
2044 /* submit URBs */
2045 for (i = 0; i < num_urbs; i++) {
2046 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2047 if (r < 0) {
2048 if (errno == ENODEV) {
2049 r = LIBUSB_ERROR_NO_DEVICE;
2050 } else {
2051 usbi_err(TRANSFER_CTX(transfer),
2052 "submiturb failed error %d errno=%d", r, errno);
2053 r = LIBUSB_ERROR_IO;
2056 /* if the first URB submission fails, we can simply free up and
2057 * return failure immediately. */
2058 if (i == 0) {
2059 usbi_dbg("first URB failed, easy peasy");
2060 free_iso_urbs(tpriv);
2061 return r;
2064 /* if it's not the first URB that failed, the situation is a bit
2065 * tricky. we must discard all previous URBs. there are
2066 * complications:
2067 * - discarding is asynchronous - discarded urbs will be reaped
2068 * later. the user must not have freed the transfer when the
2069 * discarded URBs are reaped, otherwise libusbx will be using
2070 * freed memory.
2071 * - the earlier URBs may have completed successfully and we do
2072 * not want to throw away any data.
2073 * so, in this case we discard all the previous URBs BUT we report
2074 * that the transfer was submitted successfully. then later when
2075 * the final discard completes we can report error to the user.
2077 tpriv->reap_action = SUBMIT_FAILED;
2079 /* The URBs we haven't submitted yet we count as already
2080 * retired. */
2081 tpriv->num_retired = num_urbs - i;
2082 discard_urbs(itransfer, 0, i);
2084 usbi_dbg("reporting successful submission but waiting for %d "
2085 "discards before reporting error", i);
2086 return 0;
2090 return 0;
2093 static int submit_control_transfer(struct usbi_transfer *itransfer)
2095 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2096 struct libusb_transfer *transfer =
2097 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2098 struct linux_device_handle_priv *dpriv =
2099 _device_handle_priv(transfer->dev_handle);
2100 struct usbfs_urb *urb;
2101 int r;
2103 if (tpriv->urbs)
2104 return LIBUSB_ERROR_BUSY;
2106 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2107 return LIBUSB_ERROR_INVALID_PARAM;
2109 urb = calloc(1, sizeof(struct usbfs_urb));
2110 if (!urb)
2111 return LIBUSB_ERROR_NO_MEM;
2112 tpriv->urbs = urb;
2113 tpriv->num_urbs = 1;
2114 tpriv->reap_action = NORMAL;
2116 urb->usercontext = itransfer;
2117 urb->type = USBFS_URB_TYPE_CONTROL;
2118 urb->endpoint = transfer->endpoint;
2119 urb->buffer = transfer->buffer;
2120 urb->buffer_length = transfer->length;
2122 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2123 if (r < 0) {
2124 free(urb);
2125 tpriv->urbs = NULL;
2126 if (errno == ENODEV)
2127 return LIBUSB_ERROR_NO_DEVICE;
2129 usbi_err(TRANSFER_CTX(transfer),
2130 "submiturb failed error %d errno=%d", r, errno);
2131 return LIBUSB_ERROR_IO;
2133 return 0;
2136 static int op_submit_transfer(struct usbi_transfer *itransfer)
2138 struct libusb_transfer *transfer =
2139 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2141 switch (transfer->type) {
2142 case LIBUSB_TRANSFER_TYPE_CONTROL:
2143 return submit_control_transfer(itransfer);
2144 case LIBUSB_TRANSFER_TYPE_BULK:
2145 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2146 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2147 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2148 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2149 return submit_iso_transfer(itransfer);
2150 default:
2151 usbi_err(TRANSFER_CTX(transfer),
2152 "unknown endpoint type %d", transfer->type);
2153 return LIBUSB_ERROR_INVALID_PARAM;
2157 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2159 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2160 struct libusb_transfer *transfer =
2161 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2163 switch (transfer->type) {
2164 case LIBUSB_TRANSFER_TYPE_BULK:
2165 if (tpriv->reap_action == ERROR)
2166 break;
2167 /* else, fall through */
2168 case LIBUSB_TRANSFER_TYPE_CONTROL:
2169 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2170 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2171 tpriv->reap_action = CANCELLED;
2172 break;
2173 default:
2174 usbi_err(TRANSFER_CTX(transfer),
2175 "unknown endpoint type %d", transfer->type);
2176 return LIBUSB_ERROR_INVALID_PARAM;
2179 if (!tpriv->urbs)
2180 return LIBUSB_ERROR_NOT_FOUND;
2182 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2185 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2187 struct libusb_transfer *transfer =
2188 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2189 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2191 /* urbs can be freed also in submit_transfer so lock mutex first */
2192 switch (transfer->type) {
2193 case LIBUSB_TRANSFER_TYPE_CONTROL:
2194 case LIBUSB_TRANSFER_TYPE_BULK:
2195 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2196 usbi_mutex_lock(&itransfer->lock);
2197 if (tpriv->urbs)
2198 free(tpriv->urbs);
2199 tpriv->urbs = NULL;
2200 usbi_mutex_unlock(&itransfer->lock);
2201 break;
2202 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2203 usbi_mutex_lock(&itransfer->lock);
2204 if (tpriv->iso_urbs)
2205 free_iso_urbs(tpriv);
2206 usbi_mutex_unlock(&itransfer->lock);
2207 break;
2208 default:
2209 usbi_err(TRANSFER_CTX(transfer),
2210 "unknown endpoint type %d", transfer->type);
2214 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2215 struct usbfs_urb *urb)
2217 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2218 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2219 int urb_idx = urb - tpriv->urbs;
2221 usbi_mutex_lock(&itransfer->lock);
2222 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2223 urb_idx + 1, tpriv->num_urbs);
2225 tpriv->num_retired++;
2227 if (tpriv->reap_action != NORMAL) {
2228 /* cancelled, submit_fail, or completed early */
2229 usbi_dbg("abnormal reap: urb status %d", urb->status);
2231 /* even though we're in the process of cancelling, it's possible that
2232 * we may receive some data in these URBs that we don't want to lose.
2233 * examples:
2234 * 1. while the kernel is cancelling all the packets that make up an
2235 * URB, a few of them might complete. so we get back a successful
2236 * cancellation *and* some data.
2237 * 2. we receive a short URB which marks the early completion condition,
2238 * so we start cancelling the remaining URBs. however, we're too
2239 * slow and another URB completes (or at least completes partially).
2240 * (this can't happen since we always use BULK_CONTINUATION.)
2242 * When this happens, our objectives are not to lose any "surplus" data,
2243 * and also to stick it at the end of the previously-received data
2244 * (closing any holes), so that libusbx reports the total amount of
2245 * transferred data and presents it in a contiguous chunk.
2247 if (urb->actual_length > 0) {
2248 unsigned char *target = transfer->buffer + itransfer->transferred;
2249 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2250 if (urb->buffer != target) {
2251 usbi_dbg("moving surplus data from offset %d to offset %d",
2252 (unsigned char *) urb->buffer - transfer->buffer,
2253 target - transfer->buffer);
2254 memmove(target, urb->buffer, urb->actual_length);
2256 itransfer->transferred += urb->actual_length;
2259 if (tpriv->num_retired == tpriv->num_urbs) {
2260 usbi_dbg("abnormal reap: last URB handled, reporting");
2261 if (tpriv->reap_action != COMPLETED_EARLY &&
2262 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2263 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2264 goto completed;
2266 goto out_unlock;
2269 itransfer->transferred += urb->actual_length;
2271 /* Many of these errors can occur on *any* urb of a multi-urb
2272 * transfer. When they do, we tear down the rest of the transfer.
2274 switch (urb->status) {
2275 case 0:
2276 break;
2277 case -EREMOTEIO: /* short transfer */
2278 break;
2279 case -ENOENT: /* cancelled */
2280 case -ECONNRESET:
2281 break;
2282 case -ENODEV:
2283 case -ESHUTDOWN:
2284 usbi_dbg("device removed");
2285 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2286 goto cancel_remaining;
2287 case -EPIPE:
2288 usbi_dbg("detected endpoint stall");
2289 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2290 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2291 goto cancel_remaining;
2292 case -EOVERFLOW:
2293 /* overflow can only ever occur in the last urb */
2294 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2295 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2296 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2297 goto completed;
2298 case -ETIME:
2299 case -EPROTO:
2300 case -EILSEQ:
2301 case -ECOMM:
2302 case -ENOSR:
2303 usbi_dbg("low level error %d", urb->status);
2304 tpriv->reap_action = ERROR;
2305 goto cancel_remaining;
2306 default:
2307 usbi_warn(ITRANSFER_CTX(itransfer),
2308 "unrecognised urb status %d", urb->status);
2309 tpriv->reap_action = ERROR;
2310 goto cancel_remaining;
2313 /* if we're the last urb or we got less data than requested then we're
2314 * done */
2315 if (urb_idx == tpriv->num_urbs - 1) {
2316 usbi_dbg("last URB in transfer --> complete!");
2317 goto completed;
2318 } else if (urb->actual_length < urb->buffer_length) {
2319 usbi_dbg("short transfer %d/%d --> complete!",
2320 urb->actual_length, urb->buffer_length);
2321 if (tpriv->reap_action == NORMAL)
2322 tpriv->reap_action = COMPLETED_EARLY;
2323 } else
2324 goto out_unlock;
2326 cancel_remaining:
2327 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2328 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2330 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2331 goto completed;
2333 /* cancel remaining urbs and wait for their completion before
2334 * reporting results */
2335 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2337 out_unlock:
2338 usbi_mutex_unlock(&itransfer->lock);
2339 return 0;
2341 completed:
2342 free(tpriv->urbs);
2343 tpriv->urbs = NULL;
2344 usbi_mutex_unlock(&itransfer->lock);
2345 return CANCELLED == tpriv->reap_action ?
2346 usbi_handle_transfer_cancellation(itransfer) :
2347 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2350 static int handle_iso_completion(struct usbi_transfer *itransfer,
2351 struct usbfs_urb *urb)
2353 struct libusb_transfer *transfer =
2354 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2355 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2356 int num_urbs = tpriv->num_urbs;
2357 int urb_idx = 0;
2358 int i;
2359 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2361 usbi_mutex_lock(&itransfer->lock);
2362 for (i = 0; i < num_urbs; i++) {
2363 if (urb == tpriv->iso_urbs[i]) {
2364 urb_idx = i + 1;
2365 break;
2368 if (urb_idx == 0) {
2369 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2370 usbi_mutex_unlock(&itransfer->lock);
2371 return LIBUSB_ERROR_NOT_FOUND;
2374 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2375 urb_idx, num_urbs);
2377 /* copy isochronous results back in */
2379 for (i = 0; i < urb->number_of_packets; i++) {
2380 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2381 struct libusb_iso_packet_descriptor *lib_desc =
2382 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2383 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2384 switch (urb_desc->status) {
2385 case 0:
2386 break;
2387 case -ENOENT: /* cancelled */
2388 case -ECONNRESET:
2389 break;
2390 case -ENODEV:
2391 case -ESHUTDOWN:
2392 usbi_dbg("device removed");
2393 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2394 break;
2395 case -EPIPE:
2396 usbi_dbg("detected endpoint stall");
2397 lib_desc->status = LIBUSB_TRANSFER_STALL;
2398 break;
2399 case -EOVERFLOW:
2400 usbi_dbg("overflow error");
2401 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2402 break;
2403 case -ETIME:
2404 case -EPROTO:
2405 case -EILSEQ:
2406 case -ECOMM:
2407 case -ENOSR:
2408 case -EXDEV:
2409 usbi_dbg("low-level USB error %d", urb_desc->status);
2410 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2411 break;
2412 default:
2413 usbi_warn(TRANSFER_CTX(transfer),
2414 "unrecognised urb status %d", urb_desc->status);
2415 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2416 break;
2418 lib_desc->actual_length = urb_desc->actual_length;
2421 tpriv->num_retired++;
2423 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2424 usbi_dbg("CANCEL: urb status %d", urb->status);
2426 if (tpriv->num_retired == num_urbs) {
2427 usbi_dbg("CANCEL: last URB handled, reporting");
2428 free_iso_urbs(tpriv);
2429 if (tpriv->reap_action == CANCELLED) {
2430 usbi_mutex_unlock(&itransfer->lock);
2431 return usbi_handle_transfer_cancellation(itransfer);
2432 } else {
2433 usbi_mutex_unlock(&itransfer->lock);
2434 return usbi_handle_transfer_completion(itransfer,
2435 LIBUSB_TRANSFER_ERROR);
2438 goto out;
2441 switch (urb->status) {
2442 case 0:
2443 break;
2444 case -ENOENT: /* cancelled */
2445 case -ECONNRESET:
2446 break;
2447 case -ESHUTDOWN:
2448 usbi_dbg("device removed");
2449 status = LIBUSB_TRANSFER_NO_DEVICE;
2450 break;
2451 default:
2452 usbi_warn(TRANSFER_CTX(transfer),
2453 "unrecognised urb status %d", urb->status);
2454 status = LIBUSB_TRANSFER_ERROR;
2455 break;
2458 /* if we're the last urb then we're done */
2459 if (urb_idx == num_urbs) {
2460 usbi_dbg("last URB in transfer --> complete!");
2461 free_iso_urbs(tpriv);
2462 usbi_mutex_unlock(&itransfer->lock);
2463 return usbi_handle_transfer_completion(itransfer, status);
2466 out:
2467 usbi_mutex_unlock(&itransfer->lock);
2468 return 0;
2471 static int handle_control_completion(struct usbi_transfer *itransfer,
2472 struct usbfs_urb *urb)
2474 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2475 int status;
2477 usbi_mutex_lock(&itransfer->lock);
2478 usbi_dbg("handling completion status %d", urb->status);
2480 itransfer->transferred += urb->actual_length;
2482 if (tpriv->reap_action == CANCELLED) {
2483 if (urb->status != 0 && urb->status != -ENOENT)
2484 usbi_warn(ITRANSFER_CTX(itransfer),
2485 "cancel: unrecognised urb status %d", urb->status);
2486 free(tpriv->urbs);
2487 tpriv->urbs = NULL;
2488 usbi_mutex_unlock(&itransfer->lock);
2489 return usbi_handle_transfer_cancellation(itransfer);
2492 switch (urb->status) {
2493 case 0:
2494 status = LIBUSB_TRANSFER_COMPLETED;
2495 break;
2496 case -ENOENT: /* cancelled */
2497 status = LIBUSB_TRANSFER_CANCELLED;
2498 break;
2499 case -ENODEV:
2500 case -ESHUTDOWN:
2501 usbi_dbg("device removed");
2502 status = LIBUSB_TRANSFER_NO_DEVICE;
2503 break;
2504 case -EPIPE:
2505 usbi_dbg("unsupported control request");
2506 status = LIBUSB_TRANSFER_STALL;
2507 break;
2508 case -EOVERFLOW:
2509 usbi_dbg("control overflow error");
2510 status = LIBUSB_TRANSFER_OVERFLOW;
2511 break;
2512 case -ETIME:
2513 case -EPROTO:
2514 case -EILSEQ:
2515 case -ECOMM:
2516 case -ENOSR:
2517 usbi_dbg("low-level bus error occurred");
2518 status = LIBUSB_TRANSFER_ERROR;
2519 break;
2520 default:
2521 usbi_warn(ITRANSFER_CTX(itransfer),
2522 "unrecognised urb status %d", urb->status);
2523 status = LIBUSB_TRANSFER_ERROR;
2524 break;
2527 free(tpriv->urbs);
2528 tpriv->urbs = NULL;
2529 usbi_mutex_unlock(&itransfer->lock);
2530 return usbi_handle_transfer_completion(itransfer, status);
2533 static int reap_for_handle(struct libusb_device_handle *handle)
2535 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2536 int r;
2537 struct usbfs_urb *urb;
2538 struct usbi_transfer *itransfer;
2539 struct libusb_transfer *transfer;
2541 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2542 if (r == -1 && errno == EAGAIN)
2543 return 1;
2544 if (r < 0) {
2545 if (errno == ENODEV)
2546 return LIBUSB_ERROR_NO_DEVICE;
2548 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2549 r, errno);
2550 return LIBUSB_ERROR_IO;
2553 itransfer = urb->usercontext;
2554 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2556 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2557 urb->actual_length);
2559 switch (transfer->type) {
2560 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2561 return handle_iso_completion(itransfer, urb);
2562 case LIBUSB_TRANSFER_TYPE_BULK:
2563 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2564 return handle_bulk_completion(itransfer, urb);
2565 case LIBUSB_TRANSFER_TYPE_CONTROL:
2566 return handle_control_completion(itransfer, urb);
2567 default:
2568 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2569 transfer->type);
2570 return LIBUSB_ERROR_OTHER;
2574 static int op_handle_events(struct libusb_context *ctx,
2575 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2577 int r;
2578 unsigned int i = 0;
2580 usbi_mutex_lock(&ctx->open_devs_lock);
2581 for (i = 0; i < nfds && num_ready > 0; i++) {
2582 struct pollfd *pollfd = &fds[i];
2583 struct libusb_device_handle *handle;
2584 struct linux_device_handle_priv *hpriv = NULL;
2586 if (!pollfd->revents)
2587 continue;
2589 num_ready--;
2590 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2591 hpriv = _device_handle_priv(handle);
2592 if (hpriv->fd == pollfd->fd)
2593 break;
2596 if (pollfd->revents & POLLERR) {
2597 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2598 usbi_handle_disconnect(handle);
2599 continue;
2602 do {
2603 r = reap_for_handle(handle);
2604 } while (r == 0);
2605 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2606 continue;
2607 else if (r < 0)
2608 goto out;
2611 r = 0;
2612 out:
2613 usbi_mutex_unlock(&ctx->open_devs_lock);
2614 return r;
2617 static int op_clock_gettime(int clk_id, struct timespec *tp)
2619 switch (clk_id) {
2620 case USBI_CLOCK_MONOTONIC:
2621 return clock_gettime(monotonic_clkid, tp);
2622 case USBI_CLOCK_REALTIME:
2623 return clock_gettime(CLOCK_REALTIME, tp);
2624 default:
2625 return LIBUSB_ERROR_INVALID_PARAM;
2629 #ifdef USBI_TIMERFD_AVAILABLE
2630 static clockid_t op_get_timerfd_clockid(void)
2632 return monotonic_clkid;
2635 #endif
2637 const struct usbi_os_backend linux_usbfs_backend = {
2638 .name = "Linux usbfs",
2639 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2640 .init = op_init,
2641 .exit = op_exit,
2642 .get_device_list = NULL,
2643 .get_device_descriptor = op_get_device_descriptor,
2644 .get_active_config_descriptor = op_get_active_config_descriptor,
2645 .get_config_descriptor = op_get_config_descriptor,
2647 .open = op_open,
2648 .close = op_close,
2649 .get_configuration = op_get_configuration,
2650 .set_configuration = op_set_configuration,
2651 .claim_interface = op_claim_interface,
2652 .release_interface = op_release_interface,
2654 .set_interface_altsetting = op_set_interface,
2655 .clear_halt = op_clear_halt,
2656 .reset_device = op_reset_device,
2658 .kernel_driver_active = op_kernel_driver_active,
2659 .detach_kernel_driver = op_detach_kernel_driver,
2660 .attach_kernel_driver = op_attach_kernel_driver,
2662 .destroy_device = op_destroy_device,
2664 .submit_transfer = op_submit_transfer,
2665 .cancel_transfer = op_cancel_transfer,
2666 .clear_transfer_priv = op_clear_transfer_priv,
2668 .handle_events = op_handle_events,
2670 .clock_gettime = op_clock_gettime,
2672 #ifdef USBI_TIMERFD_AVAILABLE
2673 .get_timerfd_clockid = op_get_timerfd_clockid,
2674 #endif
2676 .device_priv_size = sizeof(struct linux_device_priv),
2677 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2678 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2679 .add_iso_packet_size = 0,