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
31 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #include <sys/utsname.h>
39 #include "linux_usbfs.h"
42 * opening a usbfs node causes the device to be resumed, so we attempt to
43 * avoid this during enumeration.
45 * sysfs allows us to read the kernel's in-memory copies of device descriptors
46 * and so forth, avoiding the need to open the device:
47 * - The binary "descriptors" file was added in 2.6.23.
48 * - The "busnum" file was added in 2.6.22
49 * - The "devnum" file has been present since pre-2.6.18
50 * - the "bConfigurationValue" file has been present since pre-2.6.18
52 * If we have bConfigurationValue, busnum, and devnum, then we can determine
53 * the active configuration without having to open the usbfs node in RDWR mode.
54 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
55 * The busnum file is important as that is the only way we can relate sysfs
56 * devices to usbfs nodes.
58 * If we also have descriptors, we can obtain the device descriptor and active
59 * configuration without touching usbfs at all.
61 * The descriptors file originally only contained the active configuration
62 * descriptor alongside the device descriptor, but all configurations are
63 * included as of Linux 2.6.26.
66 /* endianness for multi-byte fields:
68 * Descriptors exposed by usbfs have the multi-byte fields in the device
69 * descriptor as host endian. Multi-byte fields in the other descriptors are
70 * bus-endian. The kernel documentation says otherwise, but it is wrong.
73 static const char *usbfs_path
= NULL
;
75 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
76 static int usbdev_names
= 0;
78 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
79 * allows us to mark URBs as being part of a specific logical transfer when
80 * we submit them to the kernel. then, on any error except a cancellation, all
81 * URBs within that transfer will be cancelled and no more URBs will be
82 * accepted for the transfer, meaning that no more data can creep in.
84 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
85 * (in either direction) except the first.
86 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
87 * last; it means that the kernel should treat a short reply as an error.
88 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
89 * transfers can't be short unless there's already some sort of error), and
90 * setting this flag is disallowed (a kernel with USB debugging enabled will
93 static int supports_flag_bulk_continuation
= -1;
95 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
96 * allows us to mark URBs that should be followed by a zero length data
97 * packet, which can be required by device- or class-specific protocols.
99 static int supports_flag_zero_packet
= -1;
101 /* clock ID for monotonic clock, as not all clock sources are available on all
102 * systems. appropriate choice made at initialization time. */
103 static clockid_t monotonic_clkid
= -1;
105 /* do we have a busnum to relate devices? this also implies that we can read
106 * the active configuration through bConfigurationValue */
107 static int sysfs_can_relate_devices
= 0;
109 /* do we have a descriptors file? */
110 static int sysfs_has_descriptors
= 0;
112 /* how many times have we initted (and not exited) ? */
113 static volatile int init_count
= 0;
115 /* Protects init_count and serializes scan_devices versus the hotplug-thread */
116 static usbi_mutex_static_t hotplug_lock
= USBI_MUTEX_INITIALIZER
;
118 static int linux_start_event_monitor(void);
119 static int linux_stop_event_monitor(void);
120 static int linux_scan_devices(struct libusb_context
*ctx
);
121 static int sysfs_scan_device(struct libusb_context
*ctx
, const char *devname
);
123 #if !defined(USE_UDEV)
124 static int linux_default_scan_devices (struct libusb_context
*ctx
);
127 struct linux_device_priv
{
129 unsigned char *dev_descriptor
;
130 unsigned char *config_descriptor
;
133 struct linux_device_handle_priv
{
140 /* submission failed after the first URB, so await cancellation/completion
141 * of all the others */
144 /* cancelled by user or timeout */
147 /* completed multi-URB transfer in non-final URB */
150 /* one or more urbs encountered a low-level error */
154 struct linux_transfer_priv
{
156 struct usbfs_urb
*urbs
;
157 struct usbfs_urb
**iso_urbs
;
160 enum reap_action reap_action
;
163 enum libusb_transfer_status reap_status
;
165 /* next iso packet in user-supplied transfer to be populated */
166 int iso_packet_offset
;
169 static void _get_usbfs_path(struct libusb_device
*dev
, char *path
)
172 snprintf(path
, PATH_MAX
, "%s/usbdev%d.%d",
173 usbfs_path
, dev
->bus_number
, dev
->device_address
);
175 snprintf(path
, PATH_MAX
, "%s/%03d/%03d",
176 usbfs_path
, dev
->bus_number
, dev
->device_address
);
179 static struct linux_device_priv
*_device_priv(struct libusb_device
*dev
)
181 return (struct linux_device_priv
*) dev
->os_priv
;
184 static struct linux_device_handle_priv
*_device_handle_priv(
185 struct libusb_device_handle
*handle
)
187 return (struct linux_device_handle_priv
*) handle
->os_priv
;
190 /* check dirent for a /dev/usbdev%d.%d name
191 * optionally return bus/device on success */
192 static int _is_usbdev_entry(struct dirent
*entry
, int *bus_p
, int *dev_p
)
196 if (sscanf(entry
->d_name
, "usbdev%d.%d", &busnum
, &devnum
) != 2)
199 usbi_dbg("found: %s", entry
->d_name
);
207 static int check_usb_vfs(const char *dirname
)
210 struct dirent
*entry
;
213 dir
= opendir(dirname
);
217 while ((entry
= readdir(dir
)) != NULL
) {
218 if (entry
->d_name
[0] == '.')
221 /* We assume if we find any files that it must be the right place */
230 static const char *find_usbfs_path(void)
232 const char *path
= "/dev/bus/usb";
233 const char *ret
= NULL
;
235 if (check_usb_vfs(path
)) {
238 path
= "/proc/bus/usb";
239 if (check_usb_vfs(path
))
243 /* look for /dev/usbdev*.* if the normal places fail */
245 struct dirent
*entry
;
251 while ((entry
= readdir(dir
)) != NULL
) {
252 if (_is_usbdev_entry(entry
, NULL
, NULL
)) {
253 /* found one; that's enough */
264 usbi_dbg("found usbfs at %s", ret
);
269 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
270 * seem to lack it). fall back to REALTIME if we have to. */
271 static clockid_t
find_monotonic_clock(void)
273 #ifdef CLOCK_MONOTONIC
277 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
278 * because it's not available through timerfd */
279 r
= clock_gettime(CLOCK_MONOTONIC
, &ts
);
281 return CLOCK_MONOTONIC
;
282 usbi_dbg("monotonic clock doesn't work, errno %d", errno
);
285 return CLOCK_REALTIME
;
288 static int kernel_version_ge(int major
, int minor
, int sublevel
)
291 int atoms
, kmajor
, kminor
, ksublevel
;
295 atoms
= sscanf(uts
.release
, "%d.%d.%d", &kmajor
, &kminor
, &ksublevel
);
304 /* kmajor == major */
306 return 0 == minor
&& 0 == sublevel
;
312 /* kminor == minor */
314 return 0 == sublevel
;
316 return ksublevel
>= sublevel
;
319 /* Return 1 if filename exists inside dirname in sysfs.
320 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
321 static int sysfs_has_file(const char *dirname
, const char *filename
)
327 snprintf(path
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
, dirname
, filename
);
328 r
= stat(path
, &statbuf
);
329 if (r
== 0 && S_ISREG(statbuf
.st_mode
))
335 static int op_init(struct libusb_context
*ctx
)
340 usbfs_path
= find_usbfs_path();
342 usbi_err(ctx
, "could not find usbfs");
343 return LIBUSB_ERROR_OTHER
;
346 if (monotonic_clkid
== -1)
347 monotonic_clkid
= find_monotonic_clock();
349 if (supports_flag_bulk_continuation
== -1) {
350 /* bulk continuation URB flag available from Linux 2.6.32 */
351 supports_flag_bulk_continuation
= kernel_version_ge(2,6,32);
352 if (supports_flag_bulk_continuation
== -1) {
353 usbi_err(ctx
, "error checking for bulk continuation support");
354 return LIBUSB_ERROR_OTHER
;
358 if (supports_flag_bulk_continuation
)
359 usbi_dbg("bulk continuation flag supported");
361 if (-1 == supports_flag_zero_packet
) {
362 /* zero length packet URB flag fixed since Linux 2.6.31 */
363 supports_flag_zero_packet
= kernel_version_ge(2,6,31);
364 if (-1 == supports_flag_zero_packet
) {
365 usbi_err(ctx
, "error checking for zero length packet support");
366 return LIBUSB_ERROR_OTHER
;
370 if (supports_flag_zero_packet
)
371 usbi_dbg("zero length packet flag supported");
373 r
= stat(SYSFS_DEVICE_PATH
, &statbuf
);
374 if (r
== 0 && S_ISDIR(statbuf
.st_mode
)) {
375 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
376 struct dirent
*entry
;
378 usbi_dbg("found usb devices in sysfs");
381 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
382 return LIBUSB_ERROR_IO
;
385 /* Make sure sysfs supports all the required files. If it
386 * does not, then usbfs will be used instead. Determine
387 * this by looping through the directories in
388 * SYSFS_DEVICE_PATH. With the assumption that there will
389 * always be subdirectories of the name usbN (usb1, usb2,
390 * etc) representing the root hubs, check the usbN
391 * subdirectories to see if they have all the needed files.
392 * This algorithm uses the usbN subdirectories (root hubs)
393 * because a device disconnection will cause a race
394 * condition regarding which files are available, sometimes
395 * causing an incorrect result. The root hubs are used
396 * because it is assumed that they will always be present.
397 * See the "sysfs vs usbfs" comment at the top of this file
398 * for more details. */
399 while ((entry
= readdir(devices
))) {
400 int has_busnum
=0, has_devnum
=0, has_descriptors
=0;
401 int has_configuration_value
=0;
403 /* Only check the usbN directories. */
404 if (strncmp(entry
->d_name
, "usb", 3) != 0)
407 /* Check for the files libusbx needs from sysfs. */
408 has_busnum
= sysfs_has_file(entry
->d_name
, "busnum");
409 has_devnum
= sysfs_has_file(entry
->d_name
, "devnum");
410 has_descriptors
= sysfs_has_file(entry
->d_name
, "descriptors");
411 has_configuration_value
= sysfs_has_file(entry
->d_name
, "bConfigurationValue");
413 if (has_busnum
&& has_devnum
&& has_configuration_value
)
414 sysfs_can_relate_devices
= 1;
416 sysfs_has_descriptors
= 1;
418 /* Only need to check until we've found ONE device which
419 has all the attributes. */
420 if (sysfs_has_descriptors
&& sysfs_can_relate_devices
)
425 /* Only use sysfs descriptors if the rest of
426 sysfs will work for libusb. */
427 if (!sysfs_can_relate_devices
)
428 sysfs_has_descriptors
= 0;
430 usbi_dbg("sysfs usb info not available");
431 sysfs_has_descriptors
= 0;
432 sysfs_can_relate_devices
= 0;
435 usbi_mutex_static_lock(&hotplug_lock
);
438 /* start up hotplug event handler */
439 r
= linux_start_event_monitor();
440 if (LIBUSB_SUCCESS
!= r
) {
441 usbi_err(ctx
, "error starting hotplug event monitor");
444 if (r
== LIBUSB_SUCCESS
)
445 r
= linux_scan_devices(ctx
);
446 usbi_mutex_static_unlock(&hotplug_lock
);
451 static void op_exit(void)
454 /* should not happen */
458 usbi_mutex_static_lock(&hotplug_lock
);
460 /* tear down event handler */
461 (void)linux_stop_event_monitor();
463 usbi_mutex_static_unlock(&hotplug_lock
);
466 static int linux_start_event_monitor(void)
468 #if defined(USE_UDEV)
469 return linux_udev_start_event_monitor();
471 return linux_netlink_start_event_monitor();
475 static int linux_stop_event_monitor(void)
477 #if defined(USE_UDEV)
478 return linux_udev_stop_event_monitor();
480 return linux_netlink_stop_event_monitor();
484 static int linux_scan_devices(struct libusb_context
*ctx
)
486 #if defined(USE_UDEV)
487 return linux_udev_scan_devices(ctx
);
489 return linux_default_scan_devices(ctx
);
493 static int usbfs_get_device_descriptor(struct libusb_device
*dev
,
494 unsigned char *buffer
)
496 struct linux_device_priv
*priv
= _device_priv(dev
);
498 /* return cached copy */
499 memcpy(buffer
, priv
->dev_descriptor
, DEVICE_DESC_LENGTH
);
503 static int _open_sysfs_attr(struct libusb_device
*dev
, const char *attr
)
505 struct linux_device_priv
*priv
= _device_priv(dev
);
506 char filename
[PATH_MAX
];
509 snprintf(filename
, PATH_MAX
, "%s/%s/%s",
510 SYSFS_DEVICE_PATH
, priv
->sysfs_dir
, attr
);
511 fd
= open(filename
, O_RDONLY
);
513 usbi_err(DEVICE_CTX(dev
),
514 "open %s failed ret=%d errno=%d", filename
, fd
, errno
);
515 return LIBUSB_ERROR_IO
;
521 /* Note only suitable for attributes which always read >= 0, < 0 is error */
522 static int __read_sysfs_attr(struct libusb_context
*ctx
,
523 const char *devname
, const char *attr
)
525 char filename
[PATH_MAX
];
529 snprintf(filename
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
,
531 f
= fopen(filename
, "r");
533 if (errno
== ENOENT
) {
534 /* File doesn't exist. Assume the device has been
535 disconnected (see trac ticket #70). */
536 return LIBUSB_ERROR_NO_DEVICE
;
538 usbi_err(ctx
, "open %s failed errno=%d", filename
, errno
);
539 return LIBUSB_ERROR_IO
;
542 r
= fscanf(f
, "%d", &value
);
545 usbi_err(ctx
, "fscanf %s returned %d, errno=%d", attr
, r
, errno
);
546 return LIBUSB_ERROR_NO_DEVICE
; /* For unplug race (trac #70) */
549 usbi_err(ctx
, "%s contains a negative value", filename
);
550 return LIBUSB_ERROR_IO
;
556 static int sysfs_get_device_descriptor(struct libusb_device
*dev
,
557 unsigned char *buffer
)
562 /* sysfs provides access to an in-memory copy of the device descriptor,
563 * so we use that rather than keeping our own copy */
565 fd
= _open_sysfs_attr(dev
, "descriptors");
569 r
= read(fd
, buffer
, DEVICE_DESC_LENGTH
);;
572 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d", fd
, errno
);
573 return LIBUSB_ERROR_IO
;
574 } else if (r
< DEVICE_DESC_LENGTH
) {
575 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, DEVICE_DESC_LENGTH
);
576 return LIBUSB_ERROR_IO
;
582 static int op_get_device_descriptor(struct libusb_device
*dev
,
583 unsigned char *buffer
, int *host_endian
)
585 if (sysfs_has_descriptors
) {
587 return sysfs_get_device_descriptor(dev
, buffer
);
590 return usbfs_get_device_descriptor(dev
, buffer
);
594 static int usbfs_get_active_config_descriptor(struct libusb_device
*dev
,
595 unsigned char *buffer
, size_t len
)
597 struct linux_device_priv
*priv
= _device_priv(dev
);
598 if (!priv
->config_descriptor
)
599 return LIBUSB_ERROR_NOT_FOUND
; /* device is unconfigured */
601 /* retrieve cached copy */
602 memcpy(buffer
, priv
->config_descriptor
, len
);
606 /* read the bConfigurationValue for a device */
607 static int sysfs_get_active_config(struct libusb_device
*dev
, int *config
)
610 char tmp
[4] = {0, 0, 0, 0};
615 fd
= _open_sysfs_attr(dev
, "bConfigurationValue");
619 r
= read(fd
, tmp
, sizeof(tmp
));
622 usbi_err(DEVICE_CTX(dev
),
623 "read bConfigurationValue failed ret=%d errno=%d", r
, errno
);
624 return LIBUSB_ERROR_IO
;
626 usbi_dbg("device unconfigured");
631 if (tmp
[sizeof(tmp
) - 1] != 0) {
632 usbi_err(DEVICE_CTX(dev
), "not null-terminated?");
633 return LIBUSB_ERROR_IO
;
634 } else if (tmp
[0] == 0) {
635 usbi_err(DEVICE_CTX(dev
), "no configuration value?");
636 return LIBUSB_ERROR_IO
;
639 num
= strtol(tmp
, &endptr
, 10);
641 usbi_err(DEVICE_CTX(dev
), "error converting '%s' to integer", tmp
);
642 return LIBUSB_ERROR_IO
;
649 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
650 * seeks to the next one. */
651 static int seek_to_next_config(struct libusb_context
*ctx
, int fd
,
654 struct libusb_config_descriptor config
;
655 unsigned char tmp
[6];
659 /* read first 6 bytes of descriptor */
660 r
= read(fd
, tmp
, sizeof(tmp
));
662 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
663 return LIBUSB_ERROR_IO
;
664 } else if (r
< sizeof(tmp
)) {
665 usbi_err(ctx
, "short descriptor read %d/%d", r
, sizeof(tmp
));
666 return LIBUSB_ERROR_IO
;
669 /* seek forward to end of config */
670 usbi_parse_descriptor(tmp
, "bbwbb", &config
, host_endian
);
671 off
= lseek(fd
, config
.wTotalLength
- sizeof(tmp
), SEEK_CUR
);
673 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
674 return LIBUSB_ERROR_IO
;
680 static int sysfs_get_active_config_descriptor(struct libusb_device
*dev
,
681 unsigned char *buffer
, size_t len
)
688 unsigned char tmp
[6];
690 r
= sysfs_get_active_config(dev
, &config
);
694 return LIBUSB_ERROR_NOT_FOUND
;
696 usbi_dbg("active configuration %d", config
);
698 /* sysfs provides access to an in-memory copy of the device descriptor,
699 * so we use that rather than keeping our own copy */
701 fd
= _open_sysfs_attr(dev
, "descriptors");
705 /* device might have been unconfigured since we read bConfigurationValue,
706 * so first check that there is any config descriptor data at all... */
707 off
= lseek(fd
, 0, SEEK_END
);
709 usbi_err(DEVICE_CTX(dev
), "end seek failed, ret=%d errno=%d",
712 return LIBUSB_ERROR_IO
;
713 } else if (off
== DEVICE_DESC_LENGTH
) {
715 return LIBUSB_ERROR_NOT_FOUND
;
718 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
720 usbi_err(DEVICE_CTX(dev
), "seek failed, ret=%d errno=%d", off
, errno
);
722 return LIBUSB_ERROR_IO
;
725 /* unbounded loop: we expect the descriptor to be present under all
728 r
= read(fd
, tmp
, sizeof(tmp
));
730 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
732 return LIBUSB_ERROR_IO
;
733 } else if (r
< sizeof(tmp
)) {
734 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, sizeof(tmp
));
735 return LIBUSB_ERROR_IO
;
738 /* check bConfigurationValue */
739 if (tmp
[5] == config
)
742 /* try the next descriptor */
743 off
= lseek(fd
, 0 - sizeof(tmp
), SEEK_CUR
);
745 return LIBUSB_ERROR_IO
;
747 r
= seek_to_next_config(DEVICE_CTX(dev
), fd
, 0);
752 to_copy
= (len
< sizeof(tmp
)) ? len
: sizeof(tmp
);
753 memcpy(buffer
, tmp
, to_copy
);
754 if (len
> sizeof(tmp
)) {
755 r
= read(fd
, buffer
+ sizeof(tmp
), len
- sizeof(tmp
));
757 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
761 usbi_dbg("device is unconfigured");
762 r
= LIBUSB_ERROR_NOT_FOUND
;
763 } else if (r
< len
- sizeof(tmp
)) {
764 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, len
);
775 int linux_get_device_address (struct libusb_context
*ctx
, int detached
,
776 uint8_t *busnum
, uint8_t *devaddr
,const char *dev_node
,
777 const char *sys_name
)
779 usbi_dbg("getting address for device: %s detached: %d", sys_name
, detached
);
780 /* can't use sysfs to read the bus and device number if the
781 * device has been detached */
782 if (!sysfs_can_relate_devices
|| detached
|| NULL
== sys_name
) {
783 if (NULL
== dev_node
) {
784 return LIBUSB_ERROR_OTHER
;
787 /* will this work with all supported kernel versions? */
788 if (!strncmp(dev_node
, "/dev/bus/usb", 12)) {
789 sscanf (dev_node
, "/dev/bus/usb/%hhd/%hhd", busnum
, devaddr
);
790 } else if (!strncmp(dev_node
, "/proc/bus/usb", 13)) {
791 sscanf (dev_node
, "/proc/bus/usb/%hhd/%hhd", busnum
, devaddr
);
794 return LIBUSB_SUCCESS
;
797 usbi_dbg("scan %s", sys_name
);
799 *busnum
= __read_sysfs_attr(ctx
, sys_name
, "busnum");
803 *devaddr
= __read_sysfs_attr(ctx
, sys_name
, "devnum");
807 usbi_dbg("bus=%d dev=%d", *busnum
, *devaddr
);
808 if (*busnum
> 255 || *devaddr
> 255)
809 return LIBUSB_ERROR_INVALID_PARAM
;
811 return LIBUSB_SUCCESS
;
814 static int op_get_active_config_descriptor(struct libusb_device
*dev
,
815 unsigned char *buffer
, size_t len
, int *host_endian
)
817 if (sysfs_has_descriptors
) {
818 return sysfs_get_active_config_descriptor(dev
, buffer
, len
);
820 return usbfs_get_active_config_descriptor(dev
, buffer
, len
);
824 /* takes a usbfs fd, attempts to find the requested config and copy a certain
825 * amount of it into an output buffer. */
826 static int get_config_descriptor(struct libusb_context
*ctx
, int fd
,
827 uint8_t config_index
, unsigned char *buffer
, size_t len
)
832 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
834 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
835 return LIBUSB_ERROR_IO
;
838 /* might need to skip some configuration descriptors to reach the
839 * requested configuration */
840 while (config_index
> 0) {
841 r
= seek_to_next_config(ctx
, fd
, 1);
847 /* read the rest of the descriptor */
848 r
= read(fd
, buffer
, len
);
850 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
851 return LIBUSB_ERROR_IO
;
852 } else if (r
< len
) {
853 usbi_err(ctx
, "short output read %d/%d", r
, len
);
859 static int op_get_config_descriptor(struct libusb_device
*dev
,
860 uint8_t config_index
, unsigned char *buffer
, size_t len
, int *host_endian
)
862 char filename
[PATH_MAX
];
866 /* always read from usbfs: sysfs only has the active descriptor
867 * this will involve waking the device up, but oh well! */
869 /* FIXME: the above is no longer true, new kernels have all descriptors
870 * in the descriptors file. but its kinda hard to detect if the kernel
871 * is sufficiently new. */
873 _get_usbfs_path(dev
, filename
);
874 fd
= open(filename
, O_RDONLY
);
876 usbi_err(DEVICE_CTX(dev
),
877 "open '%s' failed, ret=%d errno=%d", filename
, fd
, errno
);
878 return LIBUSB_ERROR_IO
;
881 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, config_index
, buffer
, len
);
886 /* cache the active config descriptor in memory. a value of -1 means that
887 * we aren't sure which one is active, so just assume the first one.
889 static int cache_active_config(struct libusb_device
*dev
, int fd
,
892 struct linux_device_priv
*priv
= _device_priv(dev
);
893 struct libusb_config_descriptor config
;
894 unsigned char tmp
[8];
899 if (active_config
== -1) {
902 r
= usbi_get_config_index_by_value(dev
, active_config
, &idx
);
906 return LIBUSB_ERROR_NOT_FOUND
;
909 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, tmp
, sizeof(tmp
));
911 usbi_err(DEVICE_CTX(dev
), "first read error %d", r
);
915 usbi_parse_descriptor(tmp
, "bbw", &config
, 0);
916 buf
= malloc(config
.wTotalLength
);
918 return LIBUSB_ERROR_NO_MEM
;
920 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, buf
,
921 config
.wTotalLength
);
927 if (priv
->config_descriptor
)
928 free(priv
->config_descriptor
);
929 priv
->config_descriptor
= buf
;
933 /* send a control message to retrieve active configuration */
934 static int usbfs_get_active_config(struct libusb_device
*dev
, int fd
)
936 unsigned char active_config
= 0;
939 struct usbfs_ctrltransfer ctrl
= {
940 .bmRequestType
= LIBUSB_ENDPOINT_IN
,
941 .bRequest
= LIBUSB_REQUEST_GET_CONFIGURATION
,
946 .data
= &active_config
949 r
= ioctl(fd
, IOCTL_USBFS_CONTROL
, &ctrl
);
952 return LIBUSB_ERROR_NO_DEVICE
;
954 /* we hit this error path frequently with buggy devices :( */
955 usbi_warn(DEVICE_CTX(dev
),
956 "get_configuration failed ret=%d errno=%d", r
, errno
);
957 return LIBUSB_ERROR_IO
;
960 return active_config
;
963 static int initialize_device(struct libusb_device
*dev
, uint8_t busnum
,
964 uint8_t devaddr
, const char *sysfs_dir
)
966 struct linux_device_priv
*priv
= _device_priv(dev
);
967 unsigned char *dev_buf
;
970 int active_config
= 0;
971 int device_configured
= 1;
974 dev
->bus_number
= busnum
;
975 dev
->device_address
= devaddr
;
978 priv
->sysfs_dir
= malloc(strlen(sysfs_dir
) + 1);
979 if (!priv
->sysfs_dir
)
980 return LIBUSB_ERROR_NO_MEM
;
981 strcpy(priv
->sysfs_dir
, sysfs_dir
);
983 /* Note speed can contain 1.5, in this case __read_sysfs_attr
984 will stop parsing at the '.' and return 1 */
985 speed
= __read_sysfs_attr(DEVICE_CTX(dev
), sysfs_dir
, "speed");
988 case 1: dev
->speed
= LIBUSB_SPEED_LOW
; break;
989 case 12: dev
->speed
= LIBUSB_SPEED_FULL
; break;
990 case 480: dev
->speed
= LIBUSB_SPEED_HIGH
; break;
991 case 5000: dev
->speed
= LIBUSB_SPEED_SUPER
; break;
993 usbi_warn(DEVICE_CTX(dev
), "Unknown device speed: %d Mbps", speed
);
998 if (sysfs_has_descriptors
)
1001 /* cache device descriptor in memory so that we can retrieve it later
1002 * without waking the device up (op_get_device_descriptor) */
1004 priv
->dev_descriptor
= NULL
;
1005 priv
->config_descriptor
= NULL
;
1007 if (sysfs_can_relate_devices
) {
1008 int tmp
= sysfs_get_active_config(dev
, &active_config
);
1011 if (active_config
== -1)
1012 device_configured
= 0;
1015 _get_usbfs_path(dev
, path
);
1016 fd
= open(path
, O_RDWR
);
1017 if (fd
< 0 && errno
== EACCES
) {
1018 fd
= open(path
, O_RDONLY
);
1019 /* if we only have read-only access to the device, we cannot
1020 * send a control message to determine the active config. just
1021 * assume the first one is active. */
1026 usbi_err(DEVICE_CTX(dev
), "open failed, ret=%d errno=%d", fd
, errno
);
1027 return LIBUSB_ERROR_IO
;
1030 if (!sysfs_can_relate_devices
) {
1031 if (active_config
== -1) {
1032 /* if we only have read-only access to the device, we cannot
1033 * send a control message to determine the active config. just
1034 * assume the first one is active. */
1035 usbi_warn(DEVICE_CTX(dev
), "access to %s is read-only; cannot "
1036 "determine active configuration descriptor", path
);
1038 active_config
= usbfs_get_active_config(dev
, fd
);
1039 if (active_config
== LIBUSB_ERROR_IO
) {
1040 /* buggy devices sometimes fail to report their active config.
1041 * assume unconfigured and continue the probing */
1042 usbi_warn(DEVICE_CTX(dev
), "couldn't query active "
1043 "configuration, assumung unconfigured");
1044 device_configured
= 0;
1045 } else if (active_config
< 0) {
1047 return active_config
;
1048 } else if (active_config
== 0) {
1049 /* some buggy devices have a configuration 0, but we're
1050 * reaching into the corner of a corner case here, so let's
1051 * not support buggy devices in these circumstances.
1052 * stick to the specs: a configuration value of 0 means
1054 usbi_dbg("active cfg 0? assuming unconfigured device");
1055 device_configured
= 0;
1060 dev_buf
= malloc(DEVICE_DESC_LENGTH
);
1063 return LIBUSB_ERROR_NO_MEM
;
1066 r
= read(fd
, dev_buf
, DEVICE_DESC_LENGTH
);
1068 usbi_err(DEVICE_CTX(dev
),
1069 "read descriptor failed ret=%d errno=%d", fd
, errno
);
1072 return LIBUSB_ERROR_IO
;
1073 } else if (r
< DEVICE_DESC_LENGTH
) {
1074 usbi_err(DEVICE_CTX(dev
), "short descriptor read (%d)", r
);
1077 return LIBUSB_ERROR_IO
;
1080 /* bit of a hack: set num_configurations now because cache_active_config()
1081 * calls usbi_get_config_index_by_value() which uses it */
1082 dev
->num_configurations
= dev_buf
[DEVICE_DESC_LENGTH
- 1];
1084 if (device_configured
) {
1085 r
= cache_active_config(dev
, fd
, active_config
);
1094 priv
->dev_descriptor
= dev_buf
;
1098 static void linux_get_parent_info(struct libusb_device
*dev
, const char *sysfs_dir
)
1100 struct libusb_context
*ctx
= DEVICE_CTX(dev
);
1101 struct libusb_device
*it
;
1102 char *parent_sysfs_dir
, *tmp
;
1103 int ret
, add_parent
= 1;
1105 /* XXX -- can we figure out the topology when using usbfs? */
1106 if (NULL
== sysfs_dir
|| 0 == strncmp(sysfs_dir
, "usb", 3)) {
1107 /* either using usbfs or finding the parent of a root hub */
1111 parent_sysfs_dir
= strdup(sysfs_dir
);
1112 if (NULL
!= (tmp
= strrchr(parent_sysfs_dir
, '.')) ||
1113 NULL
!= (tmp
= strrchr(parent_sysfs_dir
, '-'))) {
1114 dev
->port_number
= atoi(tmp
+ 1);
1117 usbi_warn(ctx
, "Can not parse sysfs_dir: %s, no parent info",
1119 free (parent_sysfs_dir
);
1123 /* is the parent a root hub? */
1124 if (NULL
== strchr(parent_sysfs_dir
, '-')) {
1125 tmp
= parent_sysfs_dir
;
1126 ret
= asprintf (&parent_sysfs_dir
, "usb%s", tmp
);
1134 /* find the parent in the context */
1135 usbi_mutex_lock(&ctx
->usb_devs_lock
);
1136 list_for_each_entry(it
, &ctx
->usb_devs
, list
, struct libusb_device
) {
1137 struct linux_device_priv
*priv
= _device_priv(it
);
1138 if (0 == strcmp (priv
->sysfs_dir
, parent_sysfs_dir
)) {
1139 dev
->parent_dev
= it
;
1143 usbi_mutex_unlock(&ctx
->usb_devs_lock
);
1145 if (!dev
->parent_dev
&& add_parent
) {
1146 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1148 sysfs_scan_device(ctx
, parent_sysfs_dir
);
1153 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev
, sysfs_dir
,
1154 dev
->parent_dev
, parent_sysfs_dir
, dev
->port_number
);
1156 free (parent_sysfs_dir
);
1159 int linux_enumerate_device(struct libusb_context
*ctx
,
1160 uint8_t busnum
, uint8_t devaddr
, const char *sysfs_dir
)
1162 unsigned long session_id
;
1163 struct libusb_device
*dev
;
1166 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1167 * will be reused. instead we should add a simple sysfs attribute with
1169 session_id
= busnum
<< 8 | devaddr
;
1170 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum
, devaddr
,
1173 if (usbi_get_device_by_session_id(ctx
, session_id
)) {
1174 /* device already exists in the context */
1175 usbi_dbg("session_id %ld already exists", session_id
);
1176 return LIBUSB_SUCCESS
;
1179 usbi_dbg("allocating new device for %d/%d (session %ld)",
1180 busnum
, devaddr
, session_id
);
1181 dev
= usbi_alloc_device(ctx
, session_id
);
1183 return LIBUSB_ERROR_NO_MEM
;
1185 r
= initialize_device(dev
, busnum
, devaddr
, sysfs_dir
);
1188 r
= usbi_sanitize_device(dev
);
1192 linux_get_parent_info(dev
, sysfs_dir
);
1195 libusb_unref_device(dev
);
1197 usbi_connect_device(dev
);
1202 void linux_hotplug_enumerate(uint8_t busnum
, uint8_t devaddr
, const char *sys_name
)
1204 struct libusb_context
*ctx
;
1206 usbi_mutex_static_lock(&active_contexts_lock
);
1207 usbi_mutex_static_lock(&hotplug_lock
);
1208 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
1209 linux_enumerate_device(ctx
, busnum
, devaddr
, sys_name
);
1211 usbi_mutex_static_unlock(&hotplug_lock
);
1212 usbi_mutex_static_unlock(&active_contexts_lock
);
1215 void linux_hotplug_disconnected(uint8_t busnum
, uint8_t devaddr
, const char *sys_name
)
1217 struct libusb_context
*ctx
;
1218 struct libusb_device
*dev
;
1220 usbi_mutex_static_lock(&active_contexts_lock
);
1221 usbi_mutex_static_lock(&hotplug_lock
);
1222 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
1223 dev
= usbi_get_device_by_session_id (ctx
, busnum
<< 8 | devaddr
);
1225 usbi_disconnect_device (dev
);
1227 usbi_err(ctx
, "device not found for session %x", busnum
<< 8 | devaddr
);
1230 usbi_mutex_static_unlock(&hotplug_lock
);
1231 usbi_mutex_static_unlock(&active_contexts_lock
);
1234 #if !defined(USE_UDEV)
1235 /* open a bus directory and adds all discovered devices to the context */
1236 static int usbfs_scan_busdir(struct libusb_context
*ctx
, uint8_t busnum
)
1239 char dirpath
[PATH_MAX
];
1240 struct dirent
*entry
;
1241 int r
= LIBUSB_ERROR_IO
;
1243 snprintf(dirpath
, PATH_MAX
, "%s/%03d", usbfs_path
, busnum
);
1244 usbi_dbg("%s", dirpath
);
1245 dir
= opendir(dirpath
);
1247 usbi_err(ctx
, "opendir '%s' failed, errno=%d", dirpath
, errno
);
1248 /* FIXME: should handle valid race conditions like hub unplugged
1249 * during directory iteration - this is not an error */
1253 while ((entry
= readdir(dir
))) {
1256 if (entry
->d_name
[0] == '.')
1259 devaddr
= atoi(entry
->d_name
);
1261 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1265 if (linux_enumerate_device(ctx
, busnum
, (uint8_t) devaddr
, NULL
)) {
1266 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1277 static int usbfs_get_device_list(struct libusb_context
*ctx
)
1279 struct dirent
*entry
;
1280 DIR *buses
= opendir(usbfs_path
);
1284 usbi_err(ctx
, "opendir buses failed errno=%d", errno
);
1285 return LIBUSB_ERROR_IO
;
1288 while ((entry
= readdir(buses
))) {
1291 if (entry
->d_name
[0] == '.')
1296 if (!_is_usbdev_entry(entry
, &busnum
, &devaddr
))
1299 r
= linux_enumerate_device(ctx
, busnum
, (uint8_t) devaddr
, NULL
);
1301 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1305 busnum
= atoi(entry
->d_name
);
1307 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1311 r
= usbfs_scan_busdir(ctx
, busnum
);
1323 static int sysfs_scan_device(struct libusb_context
*ctx
, const char *devname
)
1325 uint8_t busnum
, devaddr
;
1328 ret
= linux_get_device_address (ctx
, 0, &busnum
, &devaddr
, NULL
, devname
);
1329 if (LIBUSB_SUCCESS
!= ret
) {
1333 return linux_enumerate_device(ctx
, busnum
& 0xff, devaddr
& 0xff,
1337 #if !defined(USE_UDEV)
1338 static int sysfs_get_device_list(struct libusb_context
*ctx
)
1340 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
1341 struct dirent
*entry
;
1342 int r
= LIBUSB_ERROR_IO
;
1345 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
1349 while ((entry
= readdir(devices
))) {
1350 if ((!isdigit(entry
->d_name
[0]) && strncmp(entry
->d_name
, "usb", 3))
1351 || strchr(entry
->d_name
, ':'))
1354 if (sysfs_scan_device(ctx
, entry
->d_name
)) {
1355 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1366 static int linux_default_scan_devices (struct libusb_context
*ctx
)
1368 /* we can retrieve device list and descriptors from sysfs or usbfs.
1369 * sysfs is preferable, because if we use usbfs we end up resuming
1370 * any autosuspended USB devices. however, sysfs is not available
1371 * everywhere, so we need a usbfs fallback too.
1373 * as described in the "sysfs vs usbfs" comment at the top of this
1374 * file, sometimes we have sysfs but not enough information to
1375 * relate sysfs devices to usbfs nodes. op_init() determines the
1376 * adequacy of sysfs and sets sysfs_can_relate_devices.
1378 if (sysfs_can_relate_devices
!= 0)
1379 return sysfs_get_device_list(ctx
);
1381 return usbfs_get_device_list(ctx
);
1385 static int op_open(struct libusb_device_handle
*handle
)
1387 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
1388 char filename
[PATH_MAX
];
1391 _get_usbfs_path(handle
->dev
, filename
);
1392 usbi_dbg("opening %s", filename
);
1393 hpriv
->fd
= open(filename
, O_RDWR
);
1394 if (hpriv
->fd
< 0) {
1395 if (errno
== EACCES
) {
1396 usbi_err(HANDLE_CTX(handle
), "libusbx couldn't open USB device %s: "
1397 "Permission denied.", filename
);
1398 usbi_err(HANDLE_CTX(handle
),
1399 "libusbx requires write access to USB device nodes.");
1400 return LIBUSB_ERROR_ACCESS
;
1401 } else if (errno
== ENOENT
) {
1402 usbi_err(HANDLE_CTX(handle
), "libusbx couldn't open USB device %s: "
1403 "No such file or directory.", filename
);
1404 return LIBUSB_ERROR_NO_DEVICE
;
1406 usbi_err(HANDLE_CTX(handle
),
1407 "open failed, code %d errno %d", hpriv
->fd
, errno
);
1408 return LIBUSB_ERROR_IO
;
1412 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_GET_CAPABILITIES
, &hpriv
->caps
);
1414 if (errno
== ENOTTY
)
1415 usbi_dbg("%s: getcap not available", filename
);
1417 usbi_err(HANDLE_CTX(handle
),
1418 "%s: getcap failed (%d)", filename
, errno
);
1420 if (supports_flag_zero_packet
)
1421 hpriv
->caps
|= USBFS_CAP_ZERO_PACKET
;
1422 if (supports_flag_bulk_continuation
)
1423 hpriv
->caps
|= USBFS_CAP_BULK_CONTINUATION
;
1426 return usbi_add_pollfd(HANDLE_CTX(handle
), hpriv
->fd
, POLLOUT
);
1429 static void op_close(struct libusb_device_handle
*dev_handle
)
1431 int fd
= _device_handle_priv(dev_handle
)->fd
;
1432 usbi_remove_pollfd(HANDLE_CTX(dev_handle
), fd
);
1436 static int op_get_configuration(struct libusb_device_handle
*handle
,
1440 if (sysfs_can_relate_devices
!= 1)
1441 return LIBUSB_ERROR_NOT_SUPPORTED
;
1443 r
= sysfs_get_active_config(handle
->dev
, config
);
1447 if (*config
== -1) {
1448 usbi_err(HANDLE_CTX(handle
), "device unconfigured");
1455 static int op_set_configuration(struct libusb_device_handle
*handle
, int config
)
1457 struct linux_device_priv
*priv
= _device_priv(handle
->dev
);
1458 int fd
= _device_handle_priv(handle
)->fd
;
1459 int r
= ioctl(fd
, IOCTL_USBFS_SETCONFIG
, &config
);
1461 if (errno
== EINVAL
)
1462 return LIBUSB_ERROR_NOT_FOUND
;
1463 else if (errno
== EBUSY
)
1464 return LIBUSB_ERROR_BUSY
;
1465 else if (errno
== ENODEV
)
1466 return LIBUSB_ERROR_NO_DEVICE
;
1468 usbi_err(HANDLE_CTX(handle
), "failed, error %d errno %d", r
, errno
);
1469 return LIBUSB_ERROR_OTHER
;
1472 if (!sysfs_has_descriptors
) {
1473 /* update our cached active config descriptor */
1475 if (priv
->config_descriptor
) {
1476 free(priv
->config_descriptor
);
1477 priv
->config_descriptor
= NULL
;
1480 r
= cache_active_config(handle
->dev
, fd
, config
);
1482 usbi_warn(HANDLE_CTX(handle
),
1483 "failed to update cached config descriptor, error %d", r
);
1490 static int op_claim_interface(struct libusb_device_handle
*handle
, int iface
)
1492 int fd
= _device_handle_priv(handle
)->fd
;
1493 int r
= ioctl(fd
, IOCTL_USBFS_CLAIMINTF
, &iface
);
1495 if (errno
== ENOENT
)
1496 return LIBUSB_ERROR_NOT_FOUND
;
1497 else if (errno
== EBUSY
)
1498 return LIBUSB_ERROR_BUSY
;
1499 else if (errno
== ENODEV
)
1500 return LIBUSB_ERROR_NO_DEVICE
;
1502 usbi_err(HANDLE_CTX(handle
),
1503 "claim interface failed, error %d errno %d", r
, errno
);
1504 return LIBUSB_ERROR_OTHER
;
1509 static int op_release_interface(struct libusb_device_handle
*handle
, int iface
)
1511 int fd
= _device_handle_priv(handle
)->fd
;
1512 int r
= ioctl(fd
, IOCTL_USBFS_RELEASEINTF
, &iface
);
1514 if (errno
== ENODEV
)
1515 return LIBUSB_ERROR_NO_DEVICE
;
1517 usbi_err(HANDLE_CTX(handle
),
1518 "release interface failed, error %d errno %d", r
, errno
);
1519 return LIBUSB_ERROR_OTHER
;
1524 static int op_set_interface(struct libusb_device_handle
*handle
, int iface
,
1527 int fd
= _device_handle_priv(handle
)->fd
;
1528 struct usbfs_setinterface setintf
;
1531 setintf
.interface
= iface
;
1532 setintf
.altsetting
= altsetting
;
1533 r
= ioctl(fd
, IOCTL_USBFS_SETINTF
, &setintf
);
1535 if (errno
== EINVAL
)
1536 return LIBUSB_ERROR_NOT_FOUND
;
1537 else if (errno
== ENODEV
)
1538 return LIBUSB_ERROR_NO_DEVICE
;
1540 usbi_err(HANDLE_CTX(handle
),
1541 "setintf failed error %d errno %d", r
, errno
);
1542 return LIBUSB_ERROR_OTHER
;
1548 static int op_clear_halt(struct libusb_device_handle
*handle
,
1549 unsigned char endpoint
)
1551 int fd
= _device_handle_priv(handle
)->fd
;
1552 unsigned int _endpoint
= endpoint
;
1553 int r
= ioctl(fd
, IOCTL_USBFS_CLEAR_HALT
, &_endpoint
);
1555 if (errno
== ENOENT
)
1556 return LIBUSB_ERROR_NOT_FOUND
;
1557 else if (errno
== ENODEV
)
1558 return LIBUSB_ERROR_NO_DEVICE
;
1560 usbi_err(HANDLE_CTX(handle
),
1561 "clear_halt failed error %d errno %d", r
, errno
);
1562 return LIBUSB_ERROR_OTHER
;
1568 static int op_reset_device(struct libusb_device_handle
*handle
)
1570 int fd
= _device_handle_priv(handle
)->fd
;
1573 /* Doing a device reset will cause the usbfs driver to get unbound
1574 from any interfaces it is bound to. By voluntarily unbinding
1575 the usbfs driver ourself, we stop the kernel from rebinding
1576 the interface after reset (which would end up with the interface
1577 getting bound to the in kernel driver if any). */
1578 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1579 if (handle
->claimed_interfaces
& (1L << i
)) {
1580 op_release_interface(handle
, i
);
1584 usbi_mutex_lock(&handle
->lock
);
1585 r
= ioctl(fd
, IOCTL_USBFS_RESET
, NULL
);
1587 if (errno
== ENODEV
) {
1588 ret
= LIBUSB_ERROR_NOT_FOUND
;
1592 usbi_err(HANDLE_CTX(handle
),
1593 "reset failed error %d errno %d", r
, errno
);
1594 ret
= LIBUSB_ERROR_OTHER
;
1598 /* And re-claim any interfaces which were claimed before the reset */
1599 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1600 if (handle
->claimed_interfaces
& (1L << i
)) {
1601 r
= op_claim_interface(handle
, i
);
1603 usbi_warn(HANDLE_CTX(handle
),
1604 "failed to re-claim interface %d after reset", i
);
1605 handle
->claimed_interfaces
&= ~(1L << i
);
1610 usbi_mutex_unlock(&handle
->lock
);
1614 static int op_kernel_driver_active(struct libusb_device_handle
*handle
,
1617 int fd
= _device_handle_priv(handle
)->fd
;
1618 struct usbfs_getdriver getdrv
;
1621 getdrv
.interface
= interface
;
1622 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1624 if (errno
== ENODATA
)
1626 else if (errno
== ENODEV
)
1627 return LIBUSB_ERROR_NO_DEVICE
;
1629 usbi_err(HANDLE_CTX(handle
),
1630 "get driver failed error %d errno %d", r
, errno
);
1631 return LIBUSB_ERROR_OTHER
;
1637 static int op_detach_kernel_driver(struct libusb_device_handle
*handle
,
1640 int fd
= _device_handle_priv(handle
)->fd
;
1641 struct usbfs_ioctl command
;
1642 struct usbfs_getdriver getdrv
;
1645 command
.ifno
= interface
;
1646 command
.ioctl_code
= IOCTL_USBFS_DISCONNECT
;
1647 command
.data
= NULL
;
1649 getdrv
.interface
= interface
;
1650 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1651 if (r
== 0 && strcmp(getdrv
.driver
, "usbfs") == 0)
1652 return LIBUSB_ERROR_NOT_FOUND
;
1654 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1656 if (errno
== ENODATA
)
1657 return LIBUSB_ERROR_NOT_FOUND
;
1658 else if (errno
== EINVAL
)
1659 return LIBUSB_ERROR_INVALID_PARAM
;
1660 else if (errno
== ENODEV
)
1661 return LIBUSB_ERROR_NO_DEVICE
;
1663 usbi_err(HANDLE_CTX(handle
),
1664 "detach failed error %d errno %d", r
, errno
);
1665 return LIBUSB_ERROR_OTHER
;
1671 static int op_attach_kernel_driver(struct libusb_device_handle
*handle
,
1674 int fd
= _device_handle_priv(handle
)->fd
;
1675 struct usbfs_ioctl command
;
1678 command
.ifno
= interface
;
1679 command
.ioctl_code
= IOCTL_USBFS_CONNECT
;
1680 command
.data
= NULL
;
1682 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1684 if (errno
== ENODATA
)
1685 return LIBUSB_ERROR_NOT_FOUND
;
1686 else if (errno
== EINVAL
)
1687 return LIBUSB_ERROR_INVALID_PARAM
;
1688 else if (errno
== ENODEV
)
1689 return LIBUSB_ERROR_NO_DEVICE
;
1690 else if (errno
== EBUSY
)
1691 return LIBUSB_ERROR_BUSY
;
1693 usbi_err(HANDLE_CTX(handle
),
1694 "attach failed error %d errno %d", r
, errno
);
1695 return LIBUSB_ERROR_OTHER
;
1696 } else if (r
== 0) {
1697 return LIBUSB_ERROR_NOT_FOUND
;
1703 static void op_destroy_device(struct libusb_device
*dev
)
1705 struct linux_device_priv
*priv
= _device_priv(dev
);
1706 if (!sysfs_has_descriptors
) {
1707 if (priv
->dev_descriptor
)
1708 free(priv
->dev_descriptor
);
1709 if (priv
->config_descriptor
)
1710 free(priv
->config_descriptor
);
1712 if (priv
->sysfs_dir
)
1713 free(priv
->sysfs_dir
);
1716 /* URBs are discarded in reverse order of submission to avoid races. */
1717 static int discard_urbs(struct usbi_transfer
*itransfer
, int first
, int last_plus_one
)
1719 struct libusb_transfer
*transfer
=
1720 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1721 struct linux_transfer_priv
*tpriv
=
1722 usbi_transfer_get_os_priv(itransfer
);
1723 struct linux_device_handle_priv
*dpriv
=
1724 _device_handle_priv(transfer
->dev_handle
);
1726 struct usbfs_urb
*urb
;
1728 for (i
= last_plus_one
- 1; i
>= first
; i
--) {
1729 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
== transfer
->type
)
1730 urb
= tpriv
->iso_urbs
[i
];
1732 urb
= &tpriv
->urbs
[i
];
1734 if (0 == ioctl(dpriv
->fd
, IOCTL_USBFS_DISCARDURB
, urb
))
1737 if (EINVAL
== errno
) {
1738 usbi_dbg("URB not found --> assuming ready to be reaped");
1739 if (i
== (last_plus_one
- 1))
1740 ret
= LIBUSB_ERROR_NOT_FOUND
;
1741 } else if (ENODEV
== errno
) {
1742 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1743 ret
= LIBUSB_ERROR_NO_DEVICE
;
1745 usbi_warn(TRANSFER_CTX(transfer
),
1746 "unrecognised discard errno %d", errno
);
1747 ret
= LIBUSB_ERROR_OTHER
;
1753 static void free_iso_urbs(struct linux_transfer_priv
*tpriv
)
1756 for (i
= 0; i
< tpriv
->num_urbs
; i
++) {
1757 struct usbfs_urb
*urb
= tpriv
->iso_urbs
[i
];
1763 free(tpriv
->iso_urbs
);
1764 tpriv
->iso_urbs
= NULL
;
1767 static int submit_bulk_transfer(struct usbi_transfer
*itransfer
,
1768 unsigned char urb_type
)
1770 struct libusb_transfer
*transfer
=
1771 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1772 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1773 struct linux_device_handle_priv
*dpriv
=
1774 _device_handle_priv(transfer
->dev_handle
);
1775 struct usbfs_urb
*urbs
;
1776 int is_out
= (transfer
->endpoint
& LIBUSB_ENDPOINT_DIR_MASK
)
1777 == LIBUSB_ENDPOINT_OUT
;
1778 int bulk_buffer_len
, use_bulk_continuation
;
1784 return LIBUSB_ERROR_BUSY
;
1786 if (is_out
&& (transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
) &&
1787 !(dpriv
->caps
& USBFS_CAP_ZERO_PACKET
))
1788 return LIBUSB_ERROR_NOT_SUPPORTED
;
1791 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1792 * around this by splitting large transfers into 16k blocks, and then
1793 * submit all urbs at once. it would be simpler to submit one urb at
1794 * a time, but there is a big performance gain doing it this way.
1796 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1797 * using arbritary large transfers can still be a bad idea though, as
1798 * the kernel needs to allocate physical contiguous memory for this,
1799 * which may fail for large buffers.
1801 * The kernel solves this problem by splitting the transfer into
1802 * blocks itself when the host-controller is scatter-gather capable
1803 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1805 * Last, there is the issue of short-transfers when splitting, for
1806 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1807 * is needed, but this is not always available.
1809 if (dpriv
->caps
& USBFS_CAP_BULK_SCATTER_GATHER
) {
1810 /* Good! Just submit everything in one go */
1811 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1812 use_bulk_continuation
= 0;
1813 } else if (dpriv
->caps
& USBFS_CAP_BULK_CONTINUATION
) {
1814 /* Split the transfers and use bulk-continuation to
1815 avoid issues with short-transfers */
1816 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1817 use_bulk_continuation
= 1;
1818 } else if (dpriv
->caps
& USBFS_CAP_NO_PACKET_SIZE_LIM
) {
1819 /* Don't split, assume the kernel can alloc the buffer
1820 (otherwise the submit will fail with -ENOMEM) */
1821 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1822 use_bulk_continuation
= 0;
1824 /* Bad, splitting without bulk-continuation, short transfers
1825 which end before the last urb will not work reliable! */
1826 /* Note we don't warn here as this is "normal" on kernels <
1827 2.6.32 and not a problem for most applications */
1828 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1829 use_bulk_continuation
= 0;
1832 int num_urbs
= transfer
->length
/ bulk_buffer_len
;
1833 int last_urb_partial
= 0;
1835 if (transfer
->length
== 0) {
1837 } else if ((transfer
->length
% bulk_buffer_len
) > 0) {
1838 last_urb_partial
= 1;
1841 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs
,
1843 alloc_size
= num_urbs
* sizeof(struct usbfs_urb
);
1844 urbs
= calloc(1, alloc_size
);
1846 return LIBUSB_ERROR_NO_MEM
;
1848 tpriv
->num_urbs
= num_urbs
;
1849 tpriv
->num_retired
= 0;
1850 tpriv
->reap_action
= NORMAL
;
1851 tpriv
->reap_status
= LIBUSB_TRANSFER_COMPLETED
;
1853 for (i
= 0; i
< num_urbs
; i
++) {
1854 struct usbfs_urb
*urb
= &urbs
[i
];
1855 urb
->usercontext
= itransfer
;
1856 urb
->type
= urb_type
;
1857 urb
->endpoint
= transfer
->endpoint
;
1858 urb
->buffer
= transfer
->buffer
+ (i
* bulk_buffer_len
);
1859 /* don't set the short not ok flag for the last URB */
1860 if (use_bulk_continuation
&& !is_out
&& (i
< num_urbs
- 1))
1861 urb
->flags
= USBFS_URB_SHORT_NOT_OK
;
1862 if (i
== num_urbs
- 1 && last_urb_partial
)
1863 urb
->buffer_length
= transfer
->length
% bulk_buffer_len
;
1864 else if (transfer
->length
== 0)
1865 urb
->buffer_length
= 0;
1867 urb
->buffer_length
= bulk_buffer_len
;
1869 if (i
> 0 && use_bulk_continuation
)
1870 urb
->flags
|= USBFS_URB_BULK_CONTINUATION
;
1872 /* we have already checked that the flag is supported */
1873 if (is_out
&& i
== num_urbs
- 1 &&
1874 transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
)
1875 urb
->flags
|= USBFS_URB_ZERO_PACKET
;
1877 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
1879 if (errno
== ENODEV
) {
1880 r
= LIBUSB_ERROR_NO_DEVICE
;
1882 usbi_err(TRANSFER_CTX(transfer
),
1883 "submiturb failed error %d errno=%d", r
, errno
);
1884 r
= LIBUSB_ERROR_IO
;
1887 /* if the first URB submission fails, we can simply free up and
1888 * return failure immediately. */
1890 usbi_dbg("first URB failed, easy peasy");
1896 /* if it's not the first URB that failed, the situation is a bit
1897 * tricky. we may need to discard all previous URBs. there are
1899 * - discarding is asynchronous - discarded urbs will be reaped
1900 * later. the user must not have freed the transfer when the
1901 * discarded URBs are reaped, otherwise libusbx will be using
1903 * - the earlier URBs may have completed successfully and we do
1904 * not want to throw away any data.
1905 * - this URB failing may be no error; EREMOTEIO means that
1906 * this transfer simply didn't need all the URBs we submitted
1907 * so, we report that the transfer was submitted successfully and
1908 * in case of error we discard all previous URBs. later when
1909 * the final reap completes we can report error to the user,
1910 * or success if an earlier URB was completed successfully.
1912 tpriv
->reap_action
= EREMOTEIO
== errno
? COMPLETED_EARLY
: SUBMIT_FAILED
;
1914 /* The URBs we haven't submitted yet we count as already
1916 tpriv
->num_retired
+= num_urbs
- i
;
1918 /* If we completed short then don't try to discard. */
1919 if (COMPLETED_EARLY
== tpriv
->reap_action
)
1922 discard_urbs(itransfer
, 0, i
);
1924 usbi_dbg("reporting successful submission but waiting for %d "
1925 "discards before reporting error", i
);
1933 static int submit_iso_transfer(struct usbi_transfer
*itransfer
)
1935 struct libusb_transfer
*transfer
=
1936 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1937 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1938 struct linux_device_handle_priv
*dpriv
=
1939 _device_handle_priv(transfer
->dev_handle
);
1940 struct usbfs_urb
**urbs
;
1942 int num_packets
= transfer
->num_iso_packets
;
1944 int this_urb_len
= 0;
1946 int packet_offset
= 0;
1947 unsigned int packet_len
;
1948 unsigned char *urb_buffer
= transfer
->buffer
;
1950 if (tpriv
->iso_urbs
)
1951 return LIBUSB_ERROR_BUSY
;
1953 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1954 * into smaller units to meet such restriction, then fire off all the
1955 * units at once. it would be simpler if we just fired one unit at a time,
1956 * but there is a big performance gain through doing it this way.
1958 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1959 * using arbritary large transfers is still be a bad idea though, as
1960 * the kernel needs to allocate physical contiguous memory for this,
1961 * which may fail for large buffers.
1964 /* calculate how many URBs we need */
1965 for (i
= 0; i
< num_packets
; i
++) {
1966 unsigned int space_remaining
= MAX_ISO_BUFFER_LENGTH
- this_urb_len
;
1967 packet_len
= transfer
->iso_packet_desc
[i
].length
;
1969 if (packet_len
> space_remaining
) {
1971 this_urb_len
= packet_len
;
1973 this_urb_len
+= packet_len
;
1976 usbi_dbg("need %d 32k URBs for transfer", num_urbs
);
1978 alloc_size
= num_urbs
* sizeof(*urbs
);
1979 urbs
= calloc(1, alloc_size
);
1981 return LIBUSB_ERROR_NO_MEM
;
1983 tpriv
->iso_urbs
= urbs
;
1984 tpriv
->num_urbs
= num_urbs
;
1985 tpriv
->num_retired
= 0;
1986 tpriv
->reap_action
= NORMAL
;
1987 tpriv
->iso_packet_offset
= 0;
1989 /* allocate + initialize each URB with the correct number of packets */
1990 for (i
= 0; i
< num_urbs
; i
++) {
1991 struct usbfs_urb
*urb
;
1992 unsigned int space_remaining_in_urb
= MAX_ISO_BUFFER_LENGTH
;
1993 int urb_packet_offset
= 0;
1994 unsigned char *urb_buffer_orig
= urb_buffer
;
1998 /* swallow up all the packets we can fit into this URB */
1999 while (packet_offset
< transfer
->num_iso_packets
) {
2000 packet_len
= transfer
->iso_packet_desc
[packet_offset
].length
;
2001 if (packet_len
<= space_remaining_in_urb
) {
2003 urb_packet_offset
++;
2005 space_remaining_in_urb
-= packet_len
;
2006 urb_buffer
+= packet_len
;
2008 /* it can't fit, save it for the next URB */
2013 alloc_size
= sizeof(*urb
)
2014 + (urb_packet_offset
* sizeof(struct usbfs_iso_packet_desc
));
2015 urb
= calloc(1, alloc_size
);
2017 free_iso_urbs(tpriv
);
2018 return LIBUSB_ERROR_NO_MEM
;
2022 /* populate packet lengths */
2023 for (j
= 0, k
= packet_offset
- urb_packet_offset
;
2024 k
< packet_offset
; k
++, j
++) {
2025 packet_len
= transfer
->iso_packet_desc
[k
].length
;
2026 urb
->iso_frame_desc
[j
].length
= packet_len
;
2029 urb
->usercontext
= itransfer
;
2030 urb
->type
= USBFS_URB_TYPE_ISO
;
2031 /* FIXME: interface for non-ASAP data? */
2032 urb
->flags
= USBFS_URB_ISO_ASAP
;
2033 urb
->endpoint
= transfer
->endpoint
;
2034 urb
->number_of_packets
= urb_packet_offset
;
2035 urb
->buffer
= urb_buffer_orig
;
2039 for (i
= 0; i
< num_urbs
; i
++) {
2040 int r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urbs
[i
]);
2042 if (errno
== ENODEV
) {
2043 r
= LIBUSB_ERROR_NO_DEVICE
;
2045 usbi_err(TRANSFER_CTX(transfer
),
2046 "submiturb failed error %d errno=%d", r
, errno
);
2047 r
= LIBUSB_ERROR_IO
;
2050 /* if the first URB submission fails, we can simply free up and
2051 * return failure immediately. */
2053 usbi_dbg("first URB failed, easy peasy");
2054 free_iso_urbs(tpriv
);
2058 /* if it's not the first URB that failed, the situation is a bit
2059 * tricky. we must discard all previous URBs. there are
2061 * - discarding is asynchronous - discarded urbs will be reaped
2062 * later. the user must not have freed the transfer when the
2063 * discarded URBs are reaped, otherwise libusbx will be using
2065 * - the earlier URBs may have completed successfully and we do
2066 * not want to throw away any data.
2067 * so, in this case we discard all the previous URBs BUT we report
2068 * that the transfer was submitted successfully. then later when
2069 * the final discard completes we can report error to the user.
2071 tpriv
->reap_action
= SUBMIT_FAILED
;
2073 /* The URBs we haven't submitted yet we count as already
2075 tpriv
->num_retired
= num_urbs
- i
;
2076 discard_urbs(itransfer
, 0, i
);
2078 usbi_dbg("reporting successful submission but waiting for %d "
2079 "discards before reporting error", i
);
2087 static int submit_control_transfer(struct usbi_transfer
*itransfer
)
2089 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2090 struct libusb_transfer
*transfer
=
2091 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2092 struct linux_device_handle_priv
*dpriv
=
2093 _device_handle_priv(transfer
->dev_handle
);
2094 struct usbfs_urb
*urb
;
2098 return LIBUSB_ERROR_BUSY
;
2100 if (transfer
->length
- LIBUSB_CONTROL_SETUP_SIZE
> MAX_CTRL_BUFFER_LENGTH
)
2101 return LIBUSB_ERROR_INVALID_PARAM
;
2103 urb
= calloc(1, sizeof(struct usbfs_urb
));
2105 return LIBUSB_ERROR_NO_MEM
;
2107 tpriv
->num_urbs
= 1;
2108 tpriv
->reap_action
= NORMAL
;
2110 urb
->usercontext
= itransfer
;
2111 urb
->type
= USBFS_URB_TYPE_CONTROL
;
2112 urb
->endpoint
= transfer
->endpoint
;
2113 urb
->buffer
= transfer
->buffer
;
2114 urb
->buffer_length
= transfer
->length
;
2116 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
2120 if (errno
== ENODEV
)
2121 return LIBUSB_ERROR_NO_DEVICE
;
2123 usbi_err(TRANSFER_CTX(transfer
),
2124 "submiturb failed error %d errno=%d", r
, errno
);
2125 return LIBUSB_ERROR_IO
;
2130 static int op_submit_transfer(struct usbi_transfer
*itransfer
)
2132 struct libusb_transfer
*transfer
=
2133 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2135 switch (transfer
->type
) {
2136 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2137 return submit_control_transfer(itransfer
);
2138 case LIBUSB_TRANSFER_TYPE_BULK
:
2139 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_BULK
);
2140 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2141 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_INTERRUPT
);
2142 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2143 return submit_iso_transfer(itransfer
);
2145 usbi_err(TRANSFER_CTX(transfer
),
2146 "unknown endpoint type %d", transfer
->type
);
2147 return LIBUSB_ERROR_INVALID_PARAM
;
2151 static int op_cancel_transfer(struct usbi_transfer
*itransfer
)
2153 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2154 struct libusb_transfer
*transfer
=
2155 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2157 switch (transfer
->type
) {
2158 case LIBUSB_TRANSFER_TYPE_BULK
:
2159 if (tpriv
->reap_action
== ERROR
)
2161 /* else, fall through */
2162 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2163 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2164 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2165 tpriv
->reap_action
= CANCELLED
;
2168 usbi_err(TRANSFER_CTX(transfer
),
2169 "unknown endpoint type %d", transfer
->type
);
2170 return LIBUSB_ERROR_INVALID_PARAM
;
2174 return LIBUSB_ERROR_NOT_FOUND
;
2176 return discard_urbs(itransfer
, 0, tpriv
->num_urbs
);
2179 static void op_clear_transfer_priv(struct usbi_transfer
*itransfer
)
2181 struct libusb_transfer
*transfer
=
2182 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2183 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2185 /* urbs can be freed also in submit_transfer so lock mutex first */
2186 switch (transfer
->type
) {
2187 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2188 case LIBUSB_TRANSFER_TYPE_BULK
:
2189 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2190 usbi_mutex_lock(&itransfer
->lock
);
2194 usbi_mutex_unlock(&itransfer
->lock
);
2196 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2197 usbi_mutex_lock(&itransfer
->lock
);
2198 if (tpriv
->iso_urbs
)
2199 free_iso_urbs(tpriv
);
2200 usbi_mutex_unlock(&itransfer
->lock
);
2203 usbi_err(TRANSFER_CTX(transfer
),
2204 "unknown endpoint type %d", transfer
->type
);
2208 static int handle_bulk_completion(struct usbi_transfer
*itransfer
,
2209 struct usbfs_urb
*urb
)
2211 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2212 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2213 int urb_idx
= urb
- tpriv
->urbs
;
2215 usbi_mutex_lock(&itransfer
->lock
);
2216 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb
->status
,
2217 urb_idx
+ 1, tpriv
->num_urbs
);
2219 tpriv
->num_retired
++;
2221 if (tpriv
->reap_action
!= NORMAL
) {
2222 /* cancelled, submit_fail, or completed early */
2223 usbi_dbg("abnormal reap: urb status %d", urb
->status
);
2225 /* even though we're in the process of cancelling, it's possible that
2226 * we may receive some data in these URBs that we don't want to lose.
2228 * 1. while the kernel is cancelling all the packets that make up an
2229 * URB, a few of them might complete. so we get back a successful
2230 * cancellation *and* some data.
2231 * 2. we receive a short URB which marks the early completion condition,
2232 * so we start cancelling the remaining URBs. however, we're too
2233 * slow and another URB completes (or at least completes partially).
2234 * (this can't happen since we always use BULK_CONTINUATION.)
2236 * When this happens, our objectives are not to lose any "surplus" data,
2237 * and also to stick it at the end of the previously-received data
2238 * (closing any holes), so that libusbx reports the total amount of
2239 * transferred data and presents it in a contiguous chunk.
2241 if (urb
->actual_length
> 0) {
2242 unsigned char *target
= transfer
->buffer
+ itransfer
->transferred
;
2243 usbi_dbg("received %d bytes of surplus data", urb
->actual_length
);
2244 if (urb
->buffer
!= target
) {
2245 usbi_dbg("moving surplus data from offset %d to offset %d",
2246 (unsigned char *) urb
->buffer
- transfer
->buffer
,
2247 target
- transfer
->buffer
);
2248 memmove(target
, urb
->buffer
, urb
->actual_length
);
2250 itransfer
->transferred
+= urb
->actual_length
;
2253 if (tpriv
->num_retired
== tpriv
->num_urbs
) {
2254 usbi_dbg("abnormal reap: last URB handled, reporting");
2255 if (tpriv
->reap_action
!= COMPLETED_EARLY
&&
2256 tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2257 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2263 itransfer
->transferred
+= urb
->actual_length
;
2265 /* Many of these errors can occur on *any* urb of a multi-urb
2266 * transfer. When they do, we tear down the rest of the transfer.
2268 switch (urb
->status
) {
2271 case -EREMOTEIO
: /* short transfer */
2273 case -ENOENT
: /* cancelled */
2278 usbi_dbg("device removed");
2279 tpriv
->reap_status
= LIBUSB_TRANSFER_NO_DEVICE
;
2280 goto cancel_remaining
;
2282 usbi_dbg("detected endpoint stall");
2283 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2284 tpriv
->reap_status
= LIBUSB_TRANSFER_STALL
;
2285 goto cancel_remaining
;
2287 /* overflow can only ever occur in the last urb */
2288 usbi_dbg("overflow, actual_length=%d", urb
->actual_length
);
2289 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2290 tpriv
->reap_status
= LIBUSB_TRANSFER_OVERFLOW
;
2297 usbi_dbg("low level error %d", urb
->status
);
2298 tpriv
->reap_action
= ERROR
;
2299 goto cancel_remaining
;
2301 usbi_warn(ITRANSFER_CTX(itransfer
),
2302 "unrecognised urb status %d", urb
->status
);
2303 tpriv
->reap_action
= ERROR
;
2304 goto cancel_remaining
;
2307 /* if we're the last urb or we got less data than requested then we're
2309 if (urb_idx
== tpriv
->num_urbs
- 1) {
2310 usbi_dbg("last URB in transfer --> complete!");
2312 } else if (urb
->actual_length
< urb
->buffer_length
) {
2313 usbi_dbg("short transfer %d/%d --> complete!",
2314 urb
->actual_length
, urb
->buffer_length
);
2315 if (tpriv
->reap_action
== NORMAL
)
2316 tpriv
->reap_action
= COMPLETED_EARLY
;
2321 if (ERROR
== tpriv
->reap_action
&& LIBUSB_TRANSFER_COMPLETED
== tpriv
->reap_status
)
2322 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2324 if (tpriv
->num_retired
== tpriv
->num_urbs
) /* nothing to cancel */
2327 /* cancel remaining urbs and wait for their completion before
2328 * reporting results */
2329 discard_urbs(itransfer
, urb_idx
+ 1, tpriv
->num_urbs
);
2332 usbi_mutex_unlock(&itransfer
->lock
);
2338 usbi_mutex_unlock(&itransfer
->lock
);
2339 return CANCELLED
== tpriv
->reap_action
?
2340 usbi_handle_transfer_cancellation(itransfer
) :
2341 usbi_handle_transfer_completion(itransfer
, tpriv
->reap_status
);
2344 static int handle_iso_completion(struct usbi_transfer
*itransfer
,
2345 struct usbfs_urb
*urb
)
2347 struct libusb_transfer
*transfer
=
2348 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2349 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2350 int num_urbs
= tpriv
->num_urbs
;
2353 enum libusb_transfer_status status
= LIBUSB_TRANSFER_COMPLETED
;
2355 usbi_mutex_lock(&itransfer
->lock
);
2356 for (i
= 0; i
< num_urbs
; i
++) {
2357 if (urb
== tpriv
->iso_urbs
[i
]) {
2363 usbi_err(TRANSFER_CTX(transfer
), "could not locate urb!");
2364 usbi_mutex_unlock(&itransfer
->lock
);
2365 return LIBUSB_ERROR_NOT_FOUND
;
2368 usbi_dbg("handling completion status %d of iso urb %d/%d", urb
->status
,
2371 /* copy isochronous results back in */
2373 for (i
= 0; i
< urb
->number_of_packets
; i
++) {
2374 struct usbfs_iso_packet_desc
*urb_desc
= &urb
->iso_frame_desc
[i
];
2375 struct libusb_iso_packet_descriptor
*lib_desc
=
2376 &transfer
->iso_packet_desc
[tpriv
->iso_packet_offset
++];
2377 lib_desc
->status
= LIBUSB_TRANSFER_COMPLETED
;
2378 switch (urb_desc
->status
) {
2381 case -ENOENT
: /* cancelled */
2386 usbi_dbg("device removed");
2387 lib_desc
->status
= LIBUSB_TRANSFER_NO_DEVICE
;
2390 usbi_dbg("detected endpoint stall");
2391 lib_desc
->status
= LIBUSB_TRANSFER_STALL
;
2394 usbi_dbg("overflow error");
2395 lib_desc
->status
= LIBUSB_TRANSFER_OVERFLOW
;
2403 usbi_dbg("low-level USB error %d", urb_desc
->status
);
2404 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2407 usbi_warn(TRANSFER_CTX(transfer
),
2408 "unrecognised urb status %d", urb_desc
->status
);
2409 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2412 lib_desc
->actual_length
= urb_desc
->actual_length
;
2415 tpriv
->num_retired
++;
2417 if (tpriv
->reap_action
!= NORMAL
) { /* cancelled or submit_fail */
2418 usbi_dbg("CANCEL: urb status %d", urb
->status
);
2420 if (tpriv
->num_retired
== num_urbs
) {
2421 usbi_dbg("CANCEL: last URB handled, reporting");
2422 free_iso_urbs(tpriv
);
2423 if (tpriv
->reap_action
== CANCELLED
) {
2424 usbi_mutex_unlock(&itransfer
->lock
);
2425 return usbi_handle_transfer_cancellation(itransfer
);
2427 usbi_mutex_unlock(&itransfer
->lock
);
2428 return usbi_handle_transfer_completion(itransfer
,
2429 LIBUSB_TRANSFER_ERROR
);
2435 switch (urb
->status
) {
2438 case -ENOENT
: /* cancelled */
2442 usbi_dbg("device removed");
2443 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2446 usbi_warn(TRANSFER_CTX(transfer
),
2447 "unrecognised urb status %d", urb
->status
);
2448 status
= LIBUSB_TRANSFER_ERROR
;
2452 /* if we're the last urb then we're done */
2453 if (urb_idx
== num_urbs
) {
2454 usbi_dbg("last URB in transfer --> complete!");
2455 free_iso_urbs(tpriv
);
2456 usbi_mutex_unlock(&itransfer
->lock
);
2457 return usbi_handle_transfer_completion(itransfer
, status
);
2461 usbi_mutex_unlock(&itransfer
->lock
);
2465 static int handle_control_completion(struct usbi_transfer
*itransfer
,
2466 struct usbfs_urb
*urb
)
2468 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2471 usbi_mutex_lock(&itransfer
->lock
);
2472 usbi_dbg("handling completion status %d", urb
->status
);
2474 itransfer
->transferred
+= urb
->actual_length
;
2476 if (tpriv
->reap_action
== CANCELLED
) {
2477 if (urb
->status
!= 0 && urb
->status
!= -ENOENT
)
2478 usbi_warn(ITRANSFER_CTX(itransfer
),
2479 "cancel: unrecognised urb status %d", urb
->status
);
2482 usbi_mutex_unlock(&itransfer
->lock
);
2483 return usbi_handle_transfer_cancellation(itransfer
);
2486 switch (urb
->status
) {
2488 status
= LIBUSB_TRANSFER_COMPLETED
;
2490 case -ENOENT
: /* cancelled */
2491 status
= LIBUSB_TRANSFER_CANCELLED
;
2495 usbi_dbg("device removed");
2496 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2499 usbi_dbg("unsupported control request");
2500 status
= LIBUSB_TRANSFER_STALL
;
2503 usbi_dbg("control overflow error");
2504 status
= LIBUSB_TRANSFER_OVERFLOW
;
2511 usbi_dbg("low-level bus error occurred");
2512 status
= LIBUSB_TRANSFER_ERROR
;
2515 usbi_warn(ITRANSFER_CTX(itransfer
),
2516 "unrecognised urb status %d", urb
->status
);
2517 status
= LIBUSB_TRANSFER_ERROR
;
2523 usbi_mutex_unlock(&itransfer
->lock
);
2524 return usbi_handle_transfer_completion(itransfer
, status
);
2527 static int reap_for_handle(struct libusb_device_handle
*handle
)
2529 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
2531 struct usbfs_urb
*urb
;
2532 struct usbi_transfer
*itransfer
;
2533 struct libusb_transfer
*transfer
;
2535 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_REAPURBNDELAY
, &urb
);
2536 if (r
== -1 && errno
== EAGAIN
)
2539 if (errno
== ENODEV
)
2540 return LIBUSB_ERROR_NO_DEVICE
;
2542 usbi_err(HANDLE_CTX(handle
), "reap failed error %d errno=%d",
2544 return LIBUSB_ERROR_IO
;
2547 itransfer
= urb
->usercontext
;
2548 transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2550 usbi_dbg("urb type=%d status=%d transferred=%d", urb
->type
, urb
->status
,
2551 urb
->actual_length
);
2553 switch (transfer
->type
) {
2554 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2555 return handle_iso_completion(itransfer
, urb
);
2556 case LIBUSB_TRANSFER_TYPE_BULK
:
2557 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2558 return handle_bulk_completion(itransfer
, urb
);
2559 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2560 return handle_control_completion(itransfer
, urb
);
2562 usbi_err(HANDLE_CTX(handle
), "unrecognised endpoint type %x",
2564 return LIBUSB_ERROR_OTHER
;
2568 static int op_handle_events(struct libusb_context
*ctx
,
2569 struct pollfd
*fds
, POLL_NFDS_TYPE nfds
, int num_ready
)
2574 usbi_mutex_lock(&ctx
->open_devs_lock
);
2575 for (i
= 0; i
< nfds
&& num_ready
> 0; i
++) {
2576 struct pollfd
*pollfd
= &fds
[i
];
2577 struct libusb_device_handle
*handle
;
2578 struct linux_device_handle_priv
*hpriv
= NULL
;
2580 if (!pollfd
->revents
)
2584 list_for_each_entry(handle
, &ctx
->open_devs
, list
, struct libusb_device_handle
) {
2585 hpriv
= _device_handle_priv(handle
);
2586 if (hpriv
->fd
== pollfd
->fd
)
2590 if (pollfd
->revents
& POLLERR
) {
2591 usbi_remove_pollfd(HANDLE_CTX(handle
), hpriv
->fd
);
2592 usbi_handle_disconnect(handle
);
2597 r
= reap_for_handle(handle
);
2599 if (r
== 1 || r
== LIBUSB_ERROR_NO_DEVICE
)
2607 usbi_mutex_unlock(&ctx
->open_devs_lock
);
2611 static int op_clock_gettime(int clk_id
, struct timespec
*tp
)
2614 case USBI_CLOCK_MONOTONIC
:
2615 return clock_gettime(monotonic_clkid
, tp
);
2616 case USBI_CLOCK_REALTIME
:
2617 return clock_gettime(CLOCK_REALTIME
, tp
);
2619 return LIBUSB_ERROR_INVALID_PARAM
;
2623 #ifdef USBI_TIMERFD_AVAILABLE
2624 static clockid_t
op_get_timerfd_clockid(void)
2626 return monotonic_clkid
;
2631 const struct usbi_os_backend linux_usbfs_backend
= {
2632 .name
= "Linux usbfs",
2633 .caps
= USBI_CAP_HAS_HID_ACCESS
|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
,
2636 .get_device_list
= NULL
,
2637 .get_device_descriptor
= op_get_device_descriptor
,
2638 .get_active_config_descriptor
= op_get_active_config_descriptor
,
2639 .get_config_descriptor
= op_get_config_descriptor
,
2643 .get_configuration
= op_get_configuration
,
2644 .set_configuration
= op_set_configuration
,
2645 .claim_interface
= op_claim_interface
,
2646 .release_interface
= op_release_interface
,
2648 .set_interface_altsetting
= op_set_interface
,
2649 .clear_halt
= op_clear_halt
,
2650 .reset_device
= op_reset_device
,
2652 .kernel_driver_active
= op_kernel_driver_active
,
2653 .detach_kernel_driver
= op_detach_kernel_driver
,
2654 .attach_kernel_driver
= op_attach_kernel_driver
,
2656 .destroy_device
= op_destroy_device
,
2658 .submit_transfer
= op_submit_transfer
,
2659 .cancel_transfer
= op_cancel_transfer
,
2660 .clear_transfer_priv
= op_clear_transfer_priv
,
2662 .handle_events
= op_handle_events
,
2664 .clock_gettime
= op_clock_gettime
,
2666 #ifdef USBI_TIMERFD_AVAILABLE
2667 .get_timerfd_clockid
= op_get_timerfd_clockid
,
2670 .device_priv_size
= sizeof(struct linux_device_priv
),
2671 .device_handle_priv_size
= sizeof(struct linux_device_handle_priv
),
2672 .transfer_priv_size
= sizeof(struct linux_transfer_priv
),
2673 .add_iso_packet_size
= 0,