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
33 #include <sys/ioctl.h>
35 #include <sys/types.h>
36 #include <sys/utsname.h>
41 #include "linux_usbfs.h"
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
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
);
129 struct linux_device_priv
{
131 unsigned char *descriptors
;
133 unsigned char *config_descriptor
;
136 struct linux_device_handle_priv
{
143 /* submission failed after the first URB, so await cancellation/completion
144 * of all the others */
147 /* cancelled by user or timeout */
150 /* completed multi-URB transfer in non-final URB */
153 /* one or more urbs encountered a low-level error */
157 struct linux_transfer_priv
{
159 struct usbfs_urb
*urbs
;
160 struct usbfs_urb
**iso_urbs
;
163 enum reap_action reap_action
;
166 enum libusb_transfer_status reap_status
;
168 /* next iso packet in user-supplied transfer to be populated */
169 int iso_packet_offset
;
172 static int _get_usbfs_fd(struct libusb_device
*dev
, mode_t mode
, int silent
)
174 struct libusb_context
*ctx
= DEVICE_CTX(dev
);
179 snprintf(path
, PATH_MAX
, "%s/usbdev%d.%d",
180 usbfs_path
, dev
->bus_number
, dev
->device_address
);
182 snprintf(path
, PATH_MAX
, "%s/%03d/%03d",
183 usbfs_path
, dev
->bus_number
, dev
->device_address
);
185 fd
= open(path
, mode
);
187 return fd
; /* Success */
190 usbi_err(ctx
, "libusbx couldn't open USB device %s: %s",
191 path
, strerror(errno
));
192 if (errno
== EACCES
&& mode
== O_RDWR
)
193 usbi_err(ctx
, "libusbx requires write access to USB "
198 return LIBUSB_ERROR_ACCESS
;
200 return LIBUSB_ERROR_NO_DEVICE
;
201 return LIBUSB_ERROR_IO
;
204 static struct linux_device_priv
*_device_priv(struct libusb_device
*dev
)
206 return (struct linux_device_priv
*) dev
->os_priv
;
209 static struct linux_device_handle_priv
*_device_handle_priv(
210 struct libusb_device_handle
*handle
)
212 return (struct linux_device_handle_priv
*) handle
->os_priv
;
215 /* check dirent for a /dev/usbdev%d.%d name
216 * optionally return bus/device on success */
217 static int _is_usbdev_entry(struct dirent
*entry
, int *bus_p
, int *dev_p
)
221 if (sscanf(entry
->d_name
, "usbdev%d.%d", &busnum
, &devnum
) != 2)
224 usbi_dbg("found: %s", entry
->d_name
);
232 static int check_usb_vfs(const char *dirname
)
235 struct dirent
*entry
;
238 dir
= opendir(dirname
);
242 while ((entry
= readdir(dir
)) != NULL
) {
243 if (entry
->d_name
[0] == '.')
246 /* We assume if we find any files that it must be the right place */
255 static const char *find_usbfs_path(void)
257 const char *path
= "/dev/bus/usb";
258 const char *ret
= NULL
;
260 if (check_usb_vfs(path
)) {
263 path
= "/proc/bus/usb";
264 if (check_usb_vfs(path
))
268 /* look for /dev/usbdev*.* if the normal places fail */
270 struct dirent
*entry
;
276 while ((entry
= readdir(dir
)) != NULL
) {
277 if (_is_usbdev_entry(entry
, NULL
, NULL
)) {
278 /* found one; that's enough */
289 usbi_dbg("found usbfs at %s", ret
);
294 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
295 * seem to lack it). fall back to REALTIME if we have to. */
296 static clockid_t
find_monotonic_clock(void)
298 #ifdef CLOCK_MONOTONIC
302 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
303 * because it's not available through timerfd */
304 r
= clock_gettime(CLOCK_MONOTONIC
, &ts
);
306 return CLOCK_MONOTONIC
;
307 usbi_dbg("monotonic clock doesn't work, errno %d", errno
);
310 return CLOCK_REALTIME
;
313 static int kernel_version_ge(int major
, int minor
, int sublevel
)
316 int atoms
, kmajor
, kminor
, ksublevel
;
320 atoms
= sscanf(uts
.release
, "%d.%d.%d", &kmajor
, &kminor
, &ksublevel
);
329 /* kmajor == major */
331 return 0 == minor
&& 0 == sublevel
;
337 /* kminor == minor */
339 return 0 == sublevel
;
341 return ksublevel
>= sublevel
;
344 /* Return 1 if filename exists inside dirname in sysfs.
345 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
346 static int sysfs_has_file(const char *dirname
, const char *filename
)
352 snprintf(path
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
, dirname
, filename
);
353 r
= stat(path
, &statbuf
);
354 if (r
== 0 && S_ISREG(statbuf
.st_mode
))
360 static int op_init(struct libusb_context
*ctx
)
365 usbfs_path
= find_usbfs_path();
367 usbi_err(ctx
, "could not find usbfs");
368 return LIBUSB_ERROR_OTHER
;
371 if (monotonic_clkid
== -1)
372 monotonic_clkid
= find_monotonic_clock();
374 if (supports_flag_bulk_continuation
== -1) {
375 /* bulk continuation URB flag available from Linux 2.6.32 */
376 supports_flag_bulk_continuation
= kernel_version_ge(2,6,32);
377 if (supports_flag_bulk_continuation
== -1) {
378 usbi_err(ctx
, "error checking for bulk continuation support");
379 return LIBUSB_ERROR_OTHER
;
383 if (supports_flag_bulk_continuation
)
384 usbi_dbg("bulk continuation flag supported");
386 if (-1 == supports_flag_zero_packet
) {
387 /* zero length packet URB flag fixed since Linux 2.6.31 */
388 supports_flag_zero_packet
= kernel_version_ge(2,6,31);
389 if (-1 == supports_flag_zero_packet
) {
390 usbi_err(ctx
, "error checking for zero length packet support");
391 return LIBUSB_ERROR_OTHER
;
395 if (supports_flag_zero_packet
)
396 usbi_dbg("zero length packet flag supported");
398 r
= stat(SYSFS_DEVICE_PATH
, &statbuf
);
399 if (r
== 0 && S_ISDIR(statbuf
.st_mode
)) {
400 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
401 struct dirent
*entry
;
403 usbi_dbg("found usb devices in sysfs");
406 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
407 return LIBUSB_ERROR_IO
;
410 /* Make sure sysfs supports all the required files. If it
411 * does not, then usbfs will be used instead. Determine
412 * this by looping through the directories in
413 * SYSFS_DEVICE_PATH. With the assumption that there will
414 * always be subdirectories of the name usbN (usb1, usb2,
415 * etc) representing the root hubs, check the usbN
416 * subdirectories to see if they have all the needed files.
417 * This algorithm uses the usbN subdirectories (root hubs)
418 * because a device disconnection will cause a race
419 * condition regarding which files are available, sometimes
420 * causing an incorrect result. The root hubs are used
421 * because it is assumed that they will always be present.
422 * See the "sysfs vs usbfs" comment at the top of this file
423 * for more details. */
424 while ((entry
= readdir(devices
))) {
425 int has_busnum
=0, has_devnum
=0, has_descriptors
=0;
426 int has_configuration_value
=0;
428 /* Only check the usbN directories. */
429 if (strncmp(entry
->d_name
, "usb", 3) != 0)
432 /* Check for the files libusbx needs from sysfs. */
433 has_busnum
= sysfs_has_file(entry
->d_name
, "busnum");
434 has_devnum
= sysfs_has_file(entry
->d_name
, "devnum");
435 has_descriptors
= sysfs_has_file(entry
->d_name
, "descriptors");
436 has_configuration_value
= sysfs_has_file(entry
->d_name
, "bConfigurationValue");
438 if (has_busnum
&& has_devnum
&& has_configuration_value
)
439 sysfs_can_relate_devices
= 1;
441 sysfs_has_descriptors
= 1;
443 /* Only need to check until we've found ONE device which
444 has all the attributes. */
445 if (sysfs_has_descriptors
&& sysfs_can_relate_devices
)
450 /* Only use sysfs descriptors if the rest of
451 sysfs will work for libusb. */
452 if (!sysfs_can_relate_devices
)
453 sysfs_has_descriptors
= 0;
455 usbi_dbg("sysfs usb info not available");
456 sysfs_has_descriptors
= 0;
457 sysfs_can_relate_devices
= 0;
460 usbi_mutex_static_lock(&hotplug_lock
);
462 if (init_count
== 0) {
463 /* start up hotplug event handler */
464 r
= linux_start_event_monitor();
466 if (r
== LIBUSB_SUCCESS
) {
467 r
= linux_scan_devices(ctx
);
468 if (r
== LIBUSB_SUCCESS
)
471 linux_stop_event_monitor();
473 usbi_err(ctx
, "error starting hotplug event monitor");
474 usbi_mutex_static_unlock(&hotplug_lock
);
479 static void op_exit(void)
481 usbi_mutex_static_lock(&hotplug_lock
);
482 assert(init_count
!= 0);
484 /* tear down event handler */
485 (void)linux_stop_event_monitor();
487 usbi_mutex_static_unlock(&hotplug_lock
);
490 static int linux_start_event_monitor(void)
492 #if defined(USE_UDEV)
493 return linux_udev_start_event_monitor();
495 return linux_netlink_start_event_monitor();
499 static int linux_stop_event_monitor(void)
501 #if defined(USE_UDEV)
502 return linux_udev_stop_event_monitor();
504 return linux_netlink_stop_event_monitor();
508 static int linux_scan_devices(struct libusb_context
*ctx
)
510 #if defined(USE_UDEV)
511 return linux_udev_scan_devices(ctx
);
513 return linux_default_scan_devices(ctx
);
517 static int _open_sysfs_attr(struct libusb_device
*dev
, const char *attr
)
519 struct linux_device_priv
*priv
= _device_priv(dev
);
520 char filename
[PATH_MAX
];
523 snprintf(filename
, PATH_MAX
, "%s/%s/%s",
524 SYSFS_DEVICE_PATH
, priv
->sysfs_dir
, attr
);
525 fd
= open(filename
, O_RDONLY
);
527 usbi_err(DEVICE_CTX(dev
),
528 "open %s failed ret=%d errno=%d", filename
, fd
, errno
);
529 return LIBUSB_ERROR_IO
;
535 /* Note only suitable for attributes which always read >= 0, < 0 is error */
536 static int __read_sysfs_attr(struct libusb_context
*ctx
,
537 const char *devname
, const char *attr
)
539 char filename
[PATH_MAX
];
543 snprintf(filename
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
,
545 f
= fopen(filename
, "r");
547 if (errno
== ENOENT
) {
548 /* File doesn't exist. Assume the device has been
549 disconnected (see trac ticket #70). */
550 return LIBUSB_ERROR_NO_DEVICE
;
552 usbi_err(ctx
, "open %s failed errno=%d", filename
, errno
);
553 return LIBUSB_ERROR_IO
;
556 r
= fscanf(f
, "%d", &value
);
559 usbi_err(ctx
, "fscanf %s returned %d, errno=%d", attr
, r
, errno
);
560 return LIBUSB_ERROR_NO_DEVICE
; /* For unplug race (trac #70) */
563 usbi_err(ctx
, "%s contains a negative value", filename
);
564 return LIBUSB_ERROR_IO
;
570 static int op_get_device_descriptor(struct libusb_device
*dev
,
571 unsigned char *buffer
, int *host_endian
)
573 struct linux_device_priv
*priv
= _device_priv(dev
);
575 *host_endian
= sysfs_has_descriptors
? 0 : 1;
576 memcpy(buffer
, priv
->descriptors
, DEVICE_DESC_LENGTH
);
581 static int usbfs_get_active_config_descriptor(struct libusb_device
*dev
,
582 unsigned char *buffer
, size_t len
)
584 struct linux_device_priv
*priv
= _device_priv(dev
);
585 if (!priv
->config_descriptor
)
586 return LIBUSB_ERROR_NOT_FOUND
; /* device is unconfigured */
588 /* retrieve cached copy */
589 memcpy(buffer
, priv
->config_descriptor
, len
);
593 /* read the bConfigurationValue for a device */
594 static int sysfs_get_active_config(struct libusb_device
*dev
, int *config
)
597 char tmp
[4] = {0, 0, 0, 0};
602 fd
= _open_sysfs_attr(dev
, "bConfigurationValue");
606 r
= read(fd
, tmp
, sizeof(tmp
));
609 usbi_err(DEVICE_CTX(dev
),
610 "read bConfigurationValue failed ret=%d errno=%d", r
, errno
);
611 return LIBUSB_ERROR_IO
;
613 usbi_dbg("device unconfigured");
618 if (tmp
[sizeof(tmp
) - 1] != 0) {
619 usbi_err(DEVICE_CTX(dev
), "not null-terminated?");
620 return LIBUSB_ERROR_IO
;
621 } else if (tmp
[0] == 0) {
622 usbi_err(DEVICE_CTX(dev
), "no configuration value?");
623 return LIBUSB_ERROR_IO
;
626 num
= strtol(tmp
, &endptr
, 10);
628 usbi_err(DEVICE_CTX(dev
), "error converting '%s' to integer", tmp
);
629 return LIBUSB_ERROR_IO
;
636 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
637 * seeks to the next one. */
638 static int seek_to_next_config(struct libusb_context
*ctx
, int fd
)
640 struct libusb_config_descriptor config
;
641 unsigned char tmp
[6];
645 /* read first 6 bytes of descriptor */
646 r
= read(fd
, tmp
, sizeof(tmp
));
648 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
649 return LIBUSB_ERROR_IO
;
650 } else if (r
< sizeof(tmp
)) {
651 usbi_err(ctx
, "short descriptor read %d/%d", r
, sizeof(tmp
));
652 return LIBUSB_ERROR_IO
;
655 /* seek forward to end of config */
656 usbi_parse_descriptor(tmp
, "bbwbb", &config
, 0);
657 off
= lseek(fd
, config
.wTotalLength
- sizeof(tmp
), SEEK_CUR
);
659 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
660 return LIBUSB_ERROR_IO
;
666 static int sysfs_get_active_config_descriptor(struct libusb_device
*dev
,
667 unsigned char *buffer
, size_t len
)
674 unsigned char tmp
[6];
676 r
= sysfs_get_active_config(dev
, &config
);
680 return LIBUSB_ERROR_NOT_FOUND
;
682 usbi_dbg("active configuration %d", config
);
684 /* sysfs provides access to an in-memory copy of the device descriptor,
685 * so we use that rather than keeping our own copy */
687 fd
= _open_sysfs_attr(dev
, "descriptors");
691 /* device might have been unconfigured since we read bConfigurationValue,
692 * so first check that there is any config descriptor data at all... */
693 off
= lseek(fd
, 0, SEEK_END
);
695 usbi_err(DEVICE_CTX(dev
), "end seek failed, ret=%d errno=%d",
698 return LIBUSB_ERROR_IO
;
699 } else if (off
== DEVICE_DESC_LENGTH
) {
701 return LIBUSB_ERROR_NOT_FOUND
;
704 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
706 usbi_err(DEVICE_CTX(dev
), "seek failed, ret=%d errno=%d", off
, errno
);
708 return LIBUSB_ERROR_IO
;
711 /* unbounded loop: we expect the descriptor to be present under all
714 r
= read(fd
, tmp
, sizeof(tmp
));
716 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
718 return LIBUSB_ERROR_IO
;
719 } else if (r
< sizeof(tmp
)) {
720 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, sizeof(tmp
));
721 return LIBUSB_ERROR_IO
;
724 /* check bConfigurationValue */
725 if (tmp
[5] == config
)
728 /* try the next descriptor */
729 off
= lseek(fd
, 0 - sizeof(tmp
), SEEK_CUR
);
731 return LIBUSB_ERROR_IO
;
733 r
= seek_to_next_config(DEVICE_CTX(dev
), fd
);
738 to_copy
= (len
< sizeof(tmp
)) ? len
: sizeof(tmp
);
739 memcpy(buffer
, tmp
, to_copy
);
740 if (len
> sizeof(tmp
)) {
741 r
= read(fd
, buffer
+ sizeof(tmp
), len
- sizeof(tmp
));
743 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
747 usbi_dbg("device is unconfigured");
748 r
= LIBUSB_ERROR_NOT_FOUND
;
749 } else if (r
< len
- sizeof(tmp
)) {
750 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, len
);
761 int linux_get_device_address (struct libusb_context
*ctx
, int detached
,
762 uint8_t *busnum
, uint8_t *devaddr
,const char *dev_node
,
763 const char *sys_name
)
765 usbi_dbg("getting address for device: %s detached: %d", sys_name
, detached
);
766 /* can't use sysfs to read the bus and device number if the
767 * device has been detached */
768 if (!sysfs_can_relate_devices
|| detached
|| NULL
== sys_name
) {
769 if (NULL
== dev_node
) {
770 return LIBUSB_ERROR_OTHER
;
773 /* will this work with all supported kernel versions? */
774 if (!strncmp(dev_node
, "/dev/bus/usb", 12)) {
775 sscanf (dev_node
, "/dev/bus/usb/%hhd/%hhd", busnum
, devaddr
);
776 } else if (!strncmp(dev_node
, "/proc/bus/usb", 13)) {
777 sscanf (dev_node
, "/proc/bus/usb/%hhd/%hhd", busnum
, devaddr
);
780 return LIBUSB_SUCCESS
;
783 usbi_dbg("scan %s", sys_name
);
785 *busnum
= __read_sysfs_attr(ctx
, sys_name
, "busnum");
789 *devaddr
= __read_sysfs_attr(ctx
, sys_name
, "devnum");
793 usbi_dbg("bus=%d dev=%d", *busnum
, *devaddr
);
794 if (*busnum
> 255 || *devaddr
> 255)
795 return LIBUSB_ERROR_INVALID_PARAM
;
797 return LIBUSB_SUCCESS
;
800 static int op_get_active_config_descriptor(struct libusb_device
*dev
,
801 unsigned char *buffer
, size_t len
, int *host_endian
)
803 /* Unlike the device desc. config descs. are always in raw format */
805 if (sysfs_has_descriptors
) {
806 return sysfs_get_active_config_descriptor(dev
, buffer
, len
);
808 return usbfs_get_active_config_descriptor(dev
, buffer
, len
);
812 /* takes a usbfs fd, attempts to find the requested config and copy a certain
813 * amount of it into an output buffer. */
814 static int get_config_descriptor(struct libusb_context
*ctx
, int fd
,
815 uint8_t config_index
, unsigned char *buffer
, size_t len
)
820 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
822 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
823 return LIBUSB_ERROR_IO
;
826 /* might need to skip some configuration descriptors to reach the
827 * requested configuration */
828 while (config_index
> 0) {
829 r
= seek_to_next_config(ctx
, fd
);
835 /* read the rest of the descriptor */
836 r
= read(fd
, buffer
, len
);
838 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
839 return LIBUSB_ERROR_IO
;
840 } else if (r
< len
) {
841 usbi_err(ctx
, "short output read %d/%d", r
, len
);
847 static int op_get_config_descriptor(struct libusb_device
*dev
,
848 uint8_t config_index
, unsigned char *buffer
, size_t len
, int *host_endian
)
853 /* Unlike the device desc. config descs. are always in raw format */
856 /* always read from usbfs: sysfs only has the active descriptor
857 * this will involve waking the device up, but oh well! */
859 /* FIXME: the above is no longer true, new kernels have all descriptors
860 * in the descriptors file. but its kinda hard to detect if the kernel
861 * is sufficiently new. */
863 fd
= _get_usbfs_fd(dev
, O_RDONLY
, 0);
867 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, config_index
, buffer
, len
);
872 /* cache the active config descriptor in memory. a value of -1 means that
873 * we aren't sure which one is active, so just assume the first one.
875 static int cache_active_config(struct libusb_device
*dev
, int fd
,
878 struct linux_device_priv
*priv
= _device_priv(dev
);
879 struct libusb_config_descriptor config
;
880 unsigned char tmp
[8];
885 if (active_config
== -1) {
888 r
= usbi_get_config_index_by_value(dev
, active_config
, &idx
);
892 return LIBUSB_ERROR_NOT_FOUND
;
895 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, tmp
, sizeof(tmp
));
897 usbi_err(DEVICE_CTX(dev
), "first read error %d", r
);
901 usbi_parse_descriptor(tmp
, "bbw", &config
, 0);
902 buf
= malloc(config
.wTotalLength
);
904 return LIBUSB_ERROR_NO_MEM
;
906 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, buf
,
907 config
.wTotalLength
);
913 if (priv
->config_descriptor
)
914 free(priv
->config_descriptor
);
915 priv
->config_descriptor
= buf
;
919 /* send a control message to retrieve active configuration */
920 static int usbfs_get_active_config(struct libusb_device
*dev
, int fd
)
922 unsigned char active_config
= 0;
925 struct usbfs_ctrltransfer ctrl
= {
926 .bmRequestType
= LIBUSB_ENDPOINT_IN
,
927 .bRequest
= LIBUSB_REQUEST_GET_CONFIGURATION
,
932 .data
= &active_config
935 r
= ioctl(fd
, IOCTL_USBFS_CONTROL
, &ctrl
);
938 return LIBUSB_ERROR_NO_DEVICE
;
940 /* we hit this error path frequently with buggy devices :( */
941 usbi_warn(DEVICE_CTX(dev
),
942 "get_configuration failed ret=%d errno=%d", r
, errno
);
943 return LIBUSB_ERROR_IO
;
946 return active_config
;
949 static int initialize_device(struct libusb_device
*dev
, uint8_t busnum
,
950 uint8_t devaddr
, const char *sysfs_dir
)
952 struct linux_device_priv
*priv
= _device_priv(dev
);
953 struct libusb_context
*ctx
= DEVICE_CTX(dev
);
954 int descriptors_size
= 512; /* Begin with a 1024 byte alloc */
957 int active_config
= 0;
958 int device_configured
= 1;
961 dev
->bus_number
= busnum
;
962 dev
->device_address
= devaddr
;
965 priv
->sysfs_dir
= malloc(strlen(sysfs_dir
) + 1);
966 if (!priv
->sysfs_dir
)
967 return LIBUSB_ERROR_NO_MEM
;
968 strcpy(priv
->sysfs_dir
, sysfs_dir
);
970 /* Note speed can contain 1.5, in this case __read_sysfs_attr
971 will stop parsing at the '.' and return 1 */
972 speed
= __read_sysfs_attr(DEVICE_CTX(dev
), sysfs_dir
, "speed");
975 case 1: dev
->speed
= LIBUSB_SPEED_LOW
; break;
976 case 12: dev
->speed
= LIBUSB_SPEED_FULL
; break;
977 case 480: dev
->speed
= LIBUSB_SPEED_HIGH
; break;
978 case 5000: dev
->speed
= LIBUSB_SPEED_SUPER
; break;
980 usbi_warn(DEVICE_CTX(dev
), "Unknown device speed: %d Mbps", speed
);
985 /* cache descriptors in memory */
986 if (sysfs_has_descriptors
)
987 fd
= _open_sysfs_attr(dev
, "descriptors");
989 fd
= _get_usbfs_fd(dev
, O_RDONLY
, 0);
994 descriptors_size
*= 2;
995 priv
->descriptors
= usbi_reallocf(priv
->descriptors
,
997 if (!priv
->descriptors
) {
999 return LIBUSB_ERROR_NO_MEM
;
1001 /* usbfs has holes in the file */
1002 if (!sysfs_has_descriptors
) {
1003 memset(priv
->descriptors
+ priv
->descriptors_len
,
1004 0, descriptors_size
- priv
->descriptors_len
);
1006 r
= read(fd
, priv
->descriptors
+ priv
->descriptors_len
,
1007 descriptors_size
- priv
->descriptors_len
);
1009 usbi_err(ctx
, "read descriptor failed ret=%d errno=%d",
1012 return LIBUSB_ERROR_IO
;
1014 priv
->descriptors_len
+= r
;
1015 } while (priv
->descriptors_len
== descriptors_size
);
1019 if (priv
->descriptors_len
< DEVICE_DESC_LENGTH
) {
1020 usbi_err(ctx
, "short descriptor read (%d)",
1021 priv
->descriptors_len
);
1022 return LIBUSB_ERROR_IO
;
1025 if (sysfs_has_descriptors
)
1028 /* cache device descriptor in memory so that we can retrieve it later
1029 * without waking the device up (op_get_device_descriptor) */
1031 priv
->config_descriptor
= NULL
;
1033 if (sysfs_can_relate_devices
) {
1034 int tmp
= sysfs_get_active_config(dev
, &active_config
);
1037 if (active_config
== -1)
1038 device_configured
= 0;
1041 fd
= _get_usbfs_fd(dev
, O_RDWR
, 1);
1042 if (fd
== LIBUSB_ERROR_ACCESS
) {
1043 fd
= _get_usbfs_fd(dev
, O_RDONLY
, 0);
1044 /* if we only have read-only access to the device, we cannot
1045 * send a control message to determine the active config. just
1046 * assume the first one is active. */
1051 return LIBUSB_ERROR_IO
;
1054 if (!sysfs_can_relate_devices
) {
1055 if (active_config
== -1) {
1056 /* if we only have read-only access to the device, we cannot
1057 * send a control message to determine the active config. just
1058 * assume the first one is active. */
1059 usbi_warn(DEVICE_CTX(dev
), "access to %s is read-only; cannot "
1060 "determine active configuration descriptor", path
);
1062 active_config
= usbfs_get_active_config(dev
, fd
);
1063 if (active_config
== LIBUSB_ERROR_IO
) {
1064 /* buggy devices sometimes fail to report their active config.
1065 * assume unconfigured and continue the probing */
1066 usbi_warn(DEVICE_CTX(dev
), "couldn't query active "
1067 "configuration, assumung unconfigured");
1068 device_configured
= 0;
1069 } else if (active_config
< 0) {
1071 return active_config
;
1072 } else if (active_config
== 0) {
1073 /* some buggy devices have a configuration 0, but we're
1074 * reaching into the corner of a corner case here, so let's
1075 * not support buggy devices in these circumstances.
1076 * stick to the specs: a configuration value of 0 means
1078 usbi_dbg("active cfg 0? assuming unconfigured device");
1079 device_configured
= 0;
1084 /* bit of a hack: set num_configurations now because cache_active_config()
1085 * calls usbi_get_config_index_by_value() which uses it */
1086 dev
->num_configurations
= priv
->descriptors
[DEVICE_DESC_LENGTH
- 1];
1088 if (device_configured
)
1089 r
= cache_active_config(dev
, fd
, active_config
);
1095 static int linux_get_parent_info(struct libusb_device
*dev
, const char *sysfs_dir
)
1097 struct libusb_context
*ctx
= DEVICE_CTX(dev
);
1098 struct libusb_device
*it
;
1099 char *parent_sysfs_dir
, *tmp
;
1100 int ret
, add_parent
= 1;
1102 /* XXX -- can we figure out the topology when using usbfs? */
1103 if (NULL
== sysfs_dir
|| 0 == strncmp(sysfs_dir
, "usb", 3)) {
1104 /* either using usbfs or finding the parent of a root hub */
1105 return LIBUSB_SUCCESS
;
1108 parent_sysfs_dir
= strdup(sysfs_dir
);
1109 if (NULL
!= (tmp
= strrchr(parent_sysfs_dir
, '.')) ||
1110 NULL
!= (tmp
= strrchr(parent_sysfs_dir
, '-'))) {
1111 dev
->port_number
= atoi(tmp
+ 1);
1114 usbi_warn(ctx
, "Can not parse sysfs_dir: %s, no parent info",
1116 free (parent_sysfs_dir
);
1117 return LIBUSB_SUCCESS
;
1120 /* is the parent a root hub? */
1121 if (NULL
== strchr(parent_sysfs_dir
, '-')) {
1122 tmp
= parent_sysfs_dir
;
1123 ret
= asprintf (&parent_sysfs_dir
, "usb%s", tmp
);
1126 return LIBUSB_ERROR_NO_MEM
;
1131 /* find the parent in the context */
1132 usbi_mutex_lock(&ctx
->usb_devs_lock
);
1133 list_for_each_entry(it
, &ctx
->usb_devs
, list
, struct libusb_device
) {
1134 struct linux_device_priv
*priv
= _device_priv(it
);
1135 if (0 == strcmp (priv
->sysfs_dir
, parent_sysfs_dir
)) {
1136 dev
->parent_dev
= libusb_ref_device(it
);
1140 usbi_mutex_unlock(&ctx
->usb_devs_lock
);
1142 if (!dev
->parent_dev
&& add_parent
) {
1143 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1145 sysfs_scan_device(ctx
, parent_sysfs_dir
);
1150 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev
, sysfs_dir
,
1151 dev
->parent_dev
, parent_sysfs_dir
, dev
->port_number
);
1153 free (parent_sysfs_dir
);
1155 return LIBUSB_SUCCESS
;
1158 int linux_enumerate_device(struct libusb_context
*ctx
,
1159 uint8_t busnum
, uint8_t devaddr
, const char *sysfs_dir
)
1161 unsigned long session_id
;
1162 struct libusb_device
*dev
;
1165 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1166 * will be reused. instead we should add a simple sysfs attribute with
1168 session_id
= busnum
<< 8 | devaddr
;
1169 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum
, devaddr
,
1172 if (usbi_get_device_by_session_id(ctx
, session_id
)) {
1173 /* device already exists in the context */
1174 usbi_dbg("session_id %ld already exists", session_id
);
1175 return LIBUSB_SUCCESS
;
1178 usbi_dbg("allocating new device for %d/%d (session %ld)",
1179 busnum
, devaddr
, session_id
);
1180 dev
= usbi_alloc_device(ctx
, session_id
);
1182 return LIBUSB_ERROR_NO_MEM
;
1184 r
= initialize_device(dev
, busnum
, devaddr
, sysfs_dir
);
1187 r
= usbi_sanitize_device(dev
);
1191 r
= linux_get_parent_info(dev
, sysfs_dir
);
1196 libusb_unref_device(dev
);
1198 usbi_connect_device(dev
);
1203 void linux_hotplug_enumerate(uint8_t busnum
, uint8_t devaddr
, const char *sys_name
)
1205 struct libusb_context
*ctx
;
1207 usbi_mutex_static_lock(&active_contexts_lock
);
1208 usbi_mutex_static_lock(&hotplug_lock
);
1209 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
1210 linux_enumerate_device(ctx
, busnum
, devaddr
, sys_name
);
1212 usbi_mutex_static_unlock(&hotplug_lock
);
1213 usbi_mutex_static_unlock(&active_contexts_lock
);
1216 void linux_hotplug_disconnected(uint8_t busnum
, uint8_t devaddr
, const char *sys_name
)
1218 struct libusb_context
*ctx
;
1219 struct libusb_device
*dev
;
1220 unsigned long session_id
= busnum
<< 8 | devaddr
;
1222 usbi_mutex_static_lock(&active_contexts_lock
);
1223 usbi_mutex_static_lock(&hotplug_lock
);
1224 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
1225 dev
= usbi_get_device_by_session_id (ctx
, session_id
);
1227 usbi_disconnect_device (dev
);
1229 usbi_dbg("device not found for session %x", session_id
);
1232 usbi_mutex_static_unlock(&hotplug_lock
);
1233 usbi_mutex_static_unlock(&active_contexts_lock
);
1236 #if !defined(USE_UDEV)
1237 /* open a bus directory and adds all discovered devices to the context */
1238 static int usbfs_scan_busdir(struct libusb_context
*ctx
, uint8_t busnum
)
1241 char dirpath
[PATH_MAX
];
1242 struct dirent
*entry
;
1243 int r
= LIBUSB_ERROR_IO
;
1245 snprintf(dirpath
, PATH_MAX
, "%s/%03d", usbfs_path
, busnum
);
1246 usbi_dbg("%s", dirpath
);
1247 dir
= opendir(dirpath
);
1249 usbi_err(ctx
, "opendir '%s' failed, errno=%d", dirpath
, errno
);
1250 /* FIXME: should handle valid race conditions like hub unplugged
1251 * during directory iteration - this is not an error */
1255 while ((entry
= readdir(dir
))) {
1258 if (entry
->d_name
[0] == '.')
1261 devaddr
= atoi(entry
->d_name
);
1263 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1267 if (linux_enumerate_device(ctx
, busnum
, (uint8_t) devaddr
, NULL
)) {
1268 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1279 static int usbfs_get_device_list(struct libusb_context
*ctx
)
1281 struct dirent
*entry
;
1282 DIR *buses
= opendir(usbfs_path
);
1286 usbi_err(ctx
, "opendir buses failed errno=%d", errno
);
1287 return LIBUSB_ERROR_IO
;
1290 while ((entry
= readdir(buses
))) {
1293 if (entry
->d_name
[0] == '.')
1298 if (!_is_usbdev_entry(entry
, &busnum
, &devaddr
))
1301 r
= linux_enumerate_device(ctx
, busnum
, (uint8_t) devaddr
, NULL
);
1303 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1307 busnum
= atoi(entry
->d_name
);
1309 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1313 r
= usbfs_scan_busdir(ctx
, busnum
);
1325 static int sysfs_scan_device(struct libusb_context
*ctx
, const char *devname
)
1327 uint8_t busnum
, devaddr
;
1330 ret
= linux_get_device_address (ctx
, 0, &busnum
, &devaddr
, NULL
, devname
);
1331 if (LIBUSB_SUCCESS
!= ret
) {
1335 return linux_enumerate_device(ctx
, busnum
& 0xff, devaddr
& 0xff,
1339 #if !defined(USE_UDEV)
1340 static int sysfs_get_device_list(struct libusb_context
*ctx
)
1342 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
1343 struct dirent
*entry
;
1344 int r
= LIBUSB_ERROR_IO
;
1347 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
1351 while ((entry
= readdir(devices
))) {
1352 if ((!isdigit(entry
->d_name
[0]) && strncmp(entry
->d_name
, "usb", 3))
1353 || strchr(entry
->d_name
, ':'))
1356 if (sysfs_scan_device(ctx
, entry
->d_name
)) {
1357 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1368 static int linux_default_scan_devices (struct libusb_context
*ctx
)
1370 /* we can retrieve device list and descriptors from sysfs or usbfs.
1371 * sysfs is preferable, because if we use usbfs we end up resuming
1372 * any autosuspended USB devices. however, sysfs is not available
1373 * everywhere, so we need a usbfs fallback too.
1375 * as described in the "sysfs vs usbfs" comment at the top of this
1376 * file, sometimes we have sysfs but not enough information to
1377 * relate sysfs devices to usbfs nodes. op_init() determines the
1378 * adequacy of sysfs and sets sysfs_can_relate_devices.
1380 if (sysfs_can_relate_devices
!= 0)
1381 return sysfs_get_device_list(ctx
);
1383 return usbfs_get_device_list(ctx
);
1387 static int op_open(struct libusb_device_handle
*handle
)
1389 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
1392 hpriv
->fd
= _get_usbfs_fd(handle
->dev
, O_RDWR
, 0);
1396 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_GET_CAPABILITIES
, &hpriv
->caps
);
1398 if (errno
== ENOTTY
)
1399 usbi_dbg("getcap not available");
1401 usbi_err(HANDLE_CTX(handle
), "getcap failed (%d)", errno
);
1403 if (supports_flag_zero_packet
)
1404 hpriv
->caps
|= USBFS_CAP_ZERO_PACKET
;
1405 if (supports_flag_bulk_continuation
)
1406 hpriv
->caps
|= USBFS_CAP_BULK_CONTINUATION
;
1409 return usbi_add_pollfd(HANDLE_CTX(handle
), hpriv
->fd
, POLLOUT
);
1412 static void op_close(struct libusb_device_handle
*dev_handle
)
1414 int fd
= _device_handle_priv(dev_handle
)->fd
;
1415 usbi_remove_pollfd(HANDLE_CTX(dev_handle
), fd
);
1419 static int op_get_configuration(struct libusb_device_handle
*handle
,
1423 if (sysfs_can_relate_devices
!= 1)
1424 return LIBUSB_ERROR_NOT_SUPPORTED
;
1426 r
= sysfs_get_active_config(handle
->dev
, config
);
1430 if (*config
== -1) {
1431 usbi_err(HANDLE_CTX(handle
), "device unconfigured");
1438 static int op_set_configuration(struct libusb_device_handle
*handle
, int config
)
1440 struct linux_device_priv
*priv
= _device_priv(handle
->dev
);
1441 int fd
= _device_handle_priv(handle
)->fd
;
1442 int r
= ioctl(fd
, IOCTL_USBFS_SETCONFIG
, &config
);
1444 if (errno
== EINVAL
)
1445 return LIBUSB_ERROR_NOT_FOUND
;
1446 else if (errno
== EBUSY
)
1447 return LIBUSB_ERROR_BUSY
;
1448 else if (errno
== ENODEV
)
1449 return LIBUSB_ERROR_NO_DEVICE
;
1451 usbi_err(HANDLE_CTX(handle
), "failed, error %d errno %d", r
, errno
);
1452 return LIBUSB_ERROR_OTHER
;
1455 if (!sysfs_has_descriptors
) {
1456 /* update our cached active config descriptor */
1458 if (priv
->config_descriptor
) {
1459 free(priv
->config_descriptor
);
1460 priv
->config_descriptor
= NULL
;
1463 r
= cache_active_config(handle
->dev
, fd
, config
);
1465 usbi_warn(HANDLE_CTX(handle
),
1466 "failed to update cached config descriptor, error %d", r
);
1473 static int op_claim_interface(struct libusb_device_handle
*handle
, int iface
)
1475 int fd
= _device_handle_priv(handle
)->fd
;
1476 int r
= ioctl(fd
, IOCTL_USBFS_CLAIMINTF
, &iface
);
1478 if (errno
== ENOENT
)
1479 return LIBUSB_ERROR_NOT_FOUND
;
1480 else if (errno
== EBUSY
)
1481 return LIBUSB_ERROR_BUSY
;
1482 else if (errno
== ENODEV
)
1483 return LIBUSB_ERROR_NO_DEVICE
;
1485 usbi_err(HANDLE_CTX(handle
),
1486 "claim interface failed, error %d errno %d", r
, errno
);
1487 return LIBUSB_ERROR_OTHER
;
1492 static int op_release_interface(struct libusb_device_handle
*handle
, int iface
)
1494 int fd
= _device_handle_priv(handle
)->fd
;
1495 int r
= ioctl(fd
, IOCTL_USBFS_RELEASEINTF
, &iface
);
1497 if (errno
== ENODEV
)
1498 return LIBUSB_ERROR_NO_DEVICE
;
1500 usbi_err(HANDLE_CTX(handle
),
1501 "release interface failed, error %d errno %d", r
, errno
);
1502 return LIBUSB_ERROR_OTHER
;
1507 static int op_set_interface(struct libusb_device_handle
*handle
, int iface
,
1510 int fd
= _device_handle_priv(handle
)->fd
;
1511 struct usbfs_setinterface setintf
;
1514 setintf
.interface
= iface
;
1515 setintf
.altsetting
= altsetting
;
1516 r
= ioctl(fd
, IOCTL_USBFS_SETINTF
, &setintf
);
1518 if (errno
== EINVAL
)
1519 return LIBUSB_ERROR_NOT_FOUND
;
1520 else if (errno
== ENODEV
)
1521 return LIBUSB_ERROR_NO_DEVICE
;
1523 usbi_err(HANDLE_CTX(handle
),
1524 "setintf failed error %d errno %d", r
, errno
);
1525 return LIBUSB_ERROR_OTHER
;
1531 static int op_clear_halt(struct libusb_device_handle
*handle
,
1532 unsigned char endpoint
)
1534 int fd
= _device_handle_priv(handle
)->fd
;
1535 unsigned int _endpoint
= endpoint
;
1536 int r
= ioctl(fd
, IOCTL_USBFS_CLEAR_HALT
, &_endpoint
);
1538 if (errno
== ENOENT
)
1539 return LIBUSB_ERROR_NOT_FOUND
;
1540 else if (errno
== ENODEV
)
1541 return LIBUSB_ERROR_NO_DEVICE
;
1543 usbi_err(HANDLE_CTX(handle
),
1544 "clear_halt failed error %d errno %d", r
, errno
);
1545 return LIBUSB_ERROR_OTHER
;
1551 static int op_reset_device(struct libusb_device_handle
*handle
)
1553 int fd
= _device_handle_priv(handle
)->fd
;
1556 /* Doing a device reset will cause the usbfs driver to get unbound
1557 from any interfaces it is bound to. By voluntarily unbinding
1558 the usbfs driver ourself, we stop the kernel from rebinding
1559 the interface after reset (which would end up with the interface
1560 getting bound to the in kernel driver if any). */
1561 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1562 if (handle
->claimed_interfaces
& (1L << i
)) {
1563 op_release_interface(handle
, i
);
1567 usbi_mutex_lock(&handle
->lock
);
1568 r
= ioctl(fd
, IOCTL_USBFS_RESET
, NULL
);
1570 if (errno
== ENODEV
) {
1571 ret
= LIBUSB_ERROR_NOT_FOUND
;
1575 usbi_err(HANDLE_CTX(handle
),
1576 "reset failed error %d errno %d", r
, errno
);
1577 ret
= LIBUSB_ERROR_OTHER
;
1581 /* And re-claim any interfaces which were claimed before the reset */
1582 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1583 if (handle
->claimed_interfaces
& (1L << i
)) {
1584 r
= op_claim_interface(handle
, i
);
1586 usbi_warn(HANDLE_CTX(handle
),
1587 "failed to re-claim interface %d after reset", i
);
1588 handle
->claimed_interfaces
&= ~(1L << i
);
1593 usbi_mutex_unlock(&handle
->lock
);
1597 static int op_kernel_driver_active(struct libusb_device_handle
*handle
,
1600 int fd
= _device_handle_priv(handle
)->fd
;
1601 struct usbfs_getdriver getdrv
;
1604 getdrv
.interface
= interface
;
1605 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1607 if (errno
== ENODATA
)
1609 else if (errno
== ENODEV
)
1610 return LIBUSB_ERROR_NO_DEVICE
;
1612 usbi_err(HANDLE_CTX(handle
),
1613 "get driver failed error %d errno %d", r
, errno
);
1614 return LIBUSB_ERROR_OTHER
;
1620 static int op_detach_kernel_driver(struct libusb_device_handle
*handle
,
1623 int fd
= _device_handle_priv(handle
)->fd
;
1624 struct usbfs_ioctl command
;
1625 struct usbfs_getdriver getdrv
;
1628 command
.ifno
= interface
;
1629 command
.ioctl_code
= IOCTL_USBFS_DISCONNECT
;
1630 command
.data
= NULL
;
1632 getdrv
.interface
= interface
;
1633 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1634 if (r
== 0 && strcmp(getdrv
.driver
, "usbfs") == 0)
1635 return LIBUSB_ERROR_NOT_FOUND
;
1637 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1639 if (errno
== ENODATA
)
1640 return LIBUSB_ERROR_NOT_FOUND
;
1641 else if (errno
== EINVAL
)
1642 return LIBUSB_ERROR_INVALID_PARAM
;
1643 else if (errno
== ENODEV
)
1644 return LIBUSB_ERROR_NO_DEVICE
;
1646 usbi_err(HANDLE_CTX(handle
),
1647 "detach failed error %d errno %d", r
, errno
);
1648 return LIBUSB_ERROR_OTHER
;
1654 static int op_attach_kernel_driver(struct libusb_device_handle
*handle
,
1657 int fd
= _device_handle_priv(handle
)->fd
;
1658 struct usbfs_ioctl command
;
1661 command
.ifno
= interface
;
1662 command
.ioctl_code
= IOCTL_USBFS_CONNECT
;
1663 command
.data
= NULL
;
1665 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1667 if (errno
== ENODATA
)
1668 return LIBUSB_ERROR_NOT_FOUND
;
1669 else if (errno
== EINVAL
)
1670 return LIBUSB_ERROR_INVALID_PARAM
;
1671 else if (errno
== ENODEV
)
1672 return LIBUSB_ERROR_NO_DEVICE
;
1673 else if (errno
== EBUSY
)
1674 return LIBUSB_ERROR_BUSY
;
1676 usbi_err(HANDLE_CTX(handle
),
1677 "attach failed error %d errno %d", r
, errno
);
1678 return LIBUSB_ERROR_OTHER
;
1679 } else if (r
== 0) {
1680 return LIBUSB_ERROR_NOT_FOUND
;
1686 static void op_destroy_device(struct libusb_device
*dev
)
1688 struct linux_device_priv
*priv
= _device_priv(dev
);
1689 if (!sysfs_has_descriptors
) {
1690 if (priv
->config_descriptor
)
1691 free(priv
->config_descriptor
);
1693 if (priv
->descriptors
)
1694 free(priv
->descriptors
);
1695 if (priv
->sysfs_dir
)
1696 free(priv
->sysfs_dir
);
1699 /* URBs are discarded in reverse order of submission to avoid races. */
1700 static int discard_urbs(struct usbi_transfer
*itransfer
, int first
, int last_plus_one
)
1702 struct libusb_transfer
*transfer
=
1703 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1704 struct linux_transfer_priv
*tpriv
=
1705 usbi_transfer_get_os_priv(itransfer
);
1706 struct linux_device_handle_priv
*dpriv
=
1707 _device_handle_priv(transfer
->dev_handle
);
1709 struct usbfs_urb
*urb
;
1711 for (i
= last_plus_one
- 1; i
>= first
; i
--) {
1712 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
== transfer
->type
)
1713 urb
= tpriv
->iso_urbs
[i
];
1715 urb
= &tpriv
->urbs
[i
];
1717 if (0 == ioctl(dpriv
->fd
, IOCTL_USBFS_DISCARDURB
, urb
))
1720 if (EINVAL
== errno
) {
1721 usbi_dbg("URB not found --> assuming ready to be reaped");
1722 if (i
== (last_plus_one
- 1))
1723 ret
= LIBUSB_ERROR_NOT_FOUND
;
1724 } else if (ENODEV
== errno
) {
1725 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1726 ret
= LIBUSB_ERROR_NO_DEVICE
;
1728 usbi_warn(TRANSFER_CTX(transfer
),
1729 "unrecognised discard errno %d", errno
);
1730 ret
= LIBUSB_ERROR_OTHER
;
1736 static void free_iso_urbs(struct linux_transfer_priv
*tpriv
)
1739 for (i
= 0; i
< tpriv
->num_urbs
; i
++) {
1740 struct usbfs_urb
*urb
= tpriv
->iso_urbs
[i
];
1746 free(tpriv
->iso_urbs
);
1747 tpriv
->iso_urbs
= NULL
;
1750 static int submit_bulk_transfer(struct usbi_transfer
*itransfer
,
1751 unsigned char urb_type
)
1753 struct libusb_transfer
*transfer
=
1754 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1755 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1756 struct linux_device_handle_priv
*dpriv
=
1757 _device_handle_priv(transfer
->dev_handle
);
1758 struct usbfs_urb
*urbs
;
1759 int is_out
= (transfer
->endpoint
& LIBUSB_ENDPOINT_DIR_MASK
)
1760 == LIBUSB_ENDPOINT_OUT
;
1761 int bulk_buffer_len
, use_bulk_continuation
;
1767 return LIBUSB_ERROR_BUSY
;
1769 if (is_out
&& (transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
) &&
1770 !(dpriv
->caps
& USBFS_CAP_ZERO_PACKET
))
1771 return LIBUSB_ERROR_NOT_SUPPORTED
;
1774 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1775 * around this by splitting large transfers into 16k blocks, and then
1776 * submit all urbs at once. it would be simpler to submit one urb at
1777 * a time, but there is a big performance gain doing it this way.
1779 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1780 * using arbritary large transfers can still be a bad idea though, as
1781 * the kernel needs to allocate physical contiguous memory for this,
1782 * which may fail for large buffers.
1784 * The kernel solves this problem by splitting the transfer into
1785 * blocks itself when the host-controller is scatter-gather capable
1786 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1788 * Last, there is the issue of short-transfers when splitting, for
1789 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1790 * is needed, but this is not always available.
1792 if (dpriv
->caps
& USBFS_CAP_BULK_SCATTER_GATHER
) {
1793 /* Good! Just submit everything in one go */
1794 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1795 use_bulk_continuation
= 0;
1796 } else if (dpriv
->caps
& USBFS_CAP_BULK_CONTINUATION
) {
1797 /* Split the transfers and use bulk-continuation to
1798 avoid issues with short-transfers */
1799 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1800 use_bulk_continuation
= 1;
1801 } else if (dpriv
->caps
& USBFS_CAP_NO_PACKET_SIZE_LIM
) {
1802 /* Don't split, assume the kernel can alloc the buffer
1803 (otherwise the submit will fail with -ENOMEM) */
1804 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1805 use_bulk_continuation
= 0;
1807 /* Bad, splitting without bulk-continuation, short transfers
1808 which end before the last urb will not work reliable! */
1809 /* Note we don't warn here as this is "normal" on kernels <
1810 2.6.32 and not a problem for most applications */
1811 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1812 use_bulk_continuation
= 0;
1815 int num_urbs
= transfer
->length
/ bulk_buffer_len
;
1816 int last_urb_partial
= 0;
1818 if (transfer
->length
== 0) {
1820 } else if ((transfer
->length
% bulk_buffer_len
) > 0) {
1821 last_urb_partial
= 1;
1824 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs
,
1826 alloc_size
= num_urbs
* sizeof(struct usbfs_urb
);
1827 urbs
= calloc(1, alloc_size
);
1829 return LIBUSB_ERROR_NO_MEM
;
1831 tpriv
->num_urbs
= num_urbs
;
1832 tpriv
->num_retired
= 0;
1833 tpriv
->reap_action
= NORMAL
;
1834 tpriv
->reap_status
= LIBUSB_TRANSFER_COMPLETED
;
1836 for (i
= 0; i
< num_urbs
; i
++) {
1837 struct usbfs_urb
*urb
= &urbs
[i
];
1838 urb
->usercontext
= itransfer
;
1839 urb
->type
= urb_type
;
1840 urb
->endpoint
= transfer
->endpoint
;
1841 urb
->buffer
= transfer
->buffer
+ (i
* bulk_buffer_len
);
1842 /* don't set the short not ok flag for the last URB */
1843 if (use_bulk_continuation
&& !is_out
&& (i
< num_urbs
- 1))
1844 urb
->flags
= USBFS_URB_SHORT_NOT_OK
;
1845 if (i
== num_urbs
- 1 && last_urb_partial
)
1846 urb
->buffer_length
= transfer
->length
% bulk_buffer_len
;
1847 else if (transfer
->length
== 0)
1848 urb
->buffer_length
= 0;
1850 urb
->buffer_length
= bulk_buffer_len
;
1852 if (i
> 0 && use_bulk_continuation
)
1853 urb
->flags
|= USBFS_URB_BULK_CONTINUATION
;
1855 /* we have already checked that the flag is supported */
1856 if (is_out
&& i
== num_urbs
- 1 &&
1857 transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
)
1858 urb
->flags
|= USBFS_URB_ZERO_PACKET
;
1860 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
1862 if (errno
== ENODEV
) {
1863 r
= LIBUSB_ERROR_NO_DEVICE
;
1865 usbi_err(TRANSFER_CTX(transfer
),
1866 "submiturb failed error %d errno=%d", r
, errno
);
1867 r
= LIBUSB_ERROR_IO
;
1870 /* if the first URB submission fails, we can simply free up and
1871 * return failure immediately. */
1873 usbi_dbg("first URB failed, easy peasy");
1879 /* if it's not the first URB that failed, the situation is a bit
1880 * tricky. we may need to discard all previous URBs. there are
1882 * - discarding is asynchronous - discarded urbs will be reaped
1883 * later. the user must not have freed the transfer when the
1884 * discarded URBs are reaped, otherwise libusbx will be using
1886 * - the earlier URBs may have completed successfully and we do
1887 * not want to throw away any data.
1888 * - this URB failing may be no error; EREMOTEIO means that
1889 * this transfer simply didn't need all the URBs we submitted
1890 * so, we report that the transfer was submitted successfully and
1891 * in case of error we discard all previous URBs. later when
1892 * the final reap completes we can report error to the user,
1893 * or success if an earlier URB was completed successfully.
1895 tpriv
->reap_action
= EREMOTEIO
== errno
? COMPLETED_EARLY
: SUBMIT_FAILED
;
1897 /* The URBs we haven't submitted yet we count as already
1899 tpriv
->num_retired
+= num_urbs
- i
;
1901 /* If we completed short then don't try to discard. */
1902 if (COMPLETED_EARLY
== tpriv
->reap_action
)
1905 discard_urbs(itransfer
, 0, i
);
1907 usbi_dbg("reporting successful submission but waiting for %d "
1908 "discards before reporting error", i
);
1916 static int submit_iso_transfer(struct usbi_transfer
*itransfer
)
1918 struct libusb_transfer
*transfer
=
1919 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1920 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1921 struct linux_device_handle_priv
*dpriv
=
1922 _device_handle_priv(transfer
->dev_handle
);
1923 struct usbfs_urb
**urbs
;
1925 int num_packets
= transfer
->num_iso_packets
;
1927 int this_urb_len
= 0;
1929 int packet_offset
= 0;
1930 unsigned int packet_len
;
1931 unsigned char *urb_buffer
= transfer
->buffer
;
1933 if (tpriv
->iso_urbs
)
1934 return LIBUSB_ERROR_BUSY
;
1936 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1937 * into smaller units to meet such restriction, then fire off all the
1938 * units at once. it would be simpler if we just fired one unit at a time,
1939 * but there is a big performance gain through doing it this way.
1941 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1942 * using arbritary large transfers is still be a bad idea though, as
1943 * the kernel needs to allocate physical contiguous memory for this,
1944 * which may fail for large buffers.
1947 /* calculate how many URBs we need */
1948 for (i
= 0; i
< num_packets
; i
++) {
1949 unsigned int space_remaining
= MAX_ISO_BUFFER_LENGTH
- this_urb_len
;
1950 packet_len
= transfer
->iso_packet_desc
[i
].length
;
1952 if (packet_len
> space_remaining
) {
1954 this_urb_len
= packet_len
;
1956 this_urb_len
+= packet_len
;
1959 usbi_dbg("need %d 32k URBs for transfer", num_urbs
);
1961 alloc_size
= num_urbs
* sizeof(*urbs
);
1962 urbs
= calloc(1, alloc_size
);
1964 return LIBUSB_ERROR_NO_MEM
;
1966 tpriv
->iso_urbs
= urbs
;
1967 tpriv
->num_urbs
= num_urbs
;
1968 tpriv
->num_retired
= 0;
1969 tpriv
->reap_action
= NORMAL
;
1970 tpriv
->iso_packet_offset
= 0;
1972 /* allocate + initialize each URB with the correct number of packets */
1973 for (i
= 0; i
< num_urbs
; i
++) {
1974 struct usbfs_urb
*urb
;
1975 unsigned int space_remaining_in_urb
= MAX_ISO_BUFFER_LENGTH
;
1976 int urb_packet_offset
= 0;
1977 unsigned char *urb_buffer_orig
= urb_buffer
;
1981 /* swallow up all the packets we can fit into this URB */
1982 while (packet_offset
< transfer
->num_iso_packets
) {
1983 packet_len
= transfer
->iso_packet_desc
[packet_offset
].length
;
1984 if (packet_len
<= space_remaining_in_urb
) {
1986 urb_packet_offset
++;
1988 space_remaining_in_urb
-= packet_len
;
1989 urb_buffer
+= packet_len
;
1991 /* it can't fit, save it for the next URB */
1996 alloc_size
= sizeof(*urb
)
1997 + (urb_packet_offset
* sizeof(struct usbfs_iso_packet_desc
));
1998 urb
= calloc(1, alloc_size
);
2000 free_iso_urbs(tpriv
);
2001 return LIBUSB_ERROR_NO_MEM
;
2005 /* populate packet lengths */
2006 for (j
= 0, k
= packet_offset
- urb_packet_offset
;
2007 k
< packet_offset
; k
++, j
++) {
2008 packet_len
= transfer
->iso_packet_desc
[k
].length
;
2009 urb
->iso_frame_desc
[j
].length
= packet_len
;
2012 urb
->usercontext
= itransfer
;
2013 urb
->type
= USBFS_URB_TYPE_ISO
;
2014 /* FIXME: interface for non-ASAP data? */
2015 urb
->flags
= USBFS_URB_ISO_ASAP
;
2016 urb
->endpoint
= transfer
->endpoint
;
2017 urb
->number_of_packets
= urb_packet_offset
;
2018 urb
->buffer
= urb_buffer_orig
;
2022 for (i
= 0; i
< num_urbs
; i
++) {
2023 int r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urbs
[i
]);
2025 if (errno
== ENODEV
) {
2026 r
= LIBUSB_ERROR_NO_DEVICE
;
2028 usbi_err(TRANSFER_CTX(transfer
),
2029 "submiturb failed error %d errno=%d", r
, errno
);
2030 r
= LIBUSB_ERROR_IO
;
2033 /* if the first URB submission fails, we can simply free up and
2034 * return failure immediately. */
2036 usbi_dbg("first URB failed, easy peasy");
2037 free_iso_urbs(tpriv
);
2041 /* if it's not the first URB that failed, the situation is a bit
2042 * tricky. we must discard all previous URBs. there are
2044 * - discarding is asynchronous - discarded urbs will be reaped
2045 * later. the user must not have freed the transfer when the
2046 * discarded URBs are reaped, otherwise libusbx will be using
2048 * - the earlier URBs may have completed successfully and we do
2049 * not want to throw away any data.
2050 * so, in this case we discard all the previous URBs BUT we report
2051 * that the transfer was submitted successfully. then later when
2052 * the final discard completes we can report error to the user.
2054 tpriv
->reap_action
= SUBMIT_FAILED
;
2056 /* The URBs we haven't submitted yet we count as already
2058 tpriv
->num_retired
= num_urbs
- i
;
2059 discard_urbs(itransfer
, 0, i
);
2061 usbi_dbg("reporting successful submission but waiting for %d "
2062 "discards before reporting error", i
);
2070 static int submit_control_transfer(struct usbi_transfer
*itransfer
)
2072 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2073 struct libusb_transfer
*transfer
=
2074 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2075 struct linux_device_handle_priv
*dpriv
=
2076 _device_handle_priv(transfer
->dev_handle
);
2077 struct usbfs_urb
*urb
;
2081 return LIBUSB_ERROR_BUSY
;
2083 if (transfer
->length
- LIBUSB_CONTROL_SETUP_SIZE
> MAX_CTRL_BUFFER_LENGTH
)
2084 return LIBUSB_ERROR_INVALID_PARAM
;
2086 urb
= calloc(1, sizeof(struct usbfs_urb
));
2088 return LIBUSB_ERROR_NO_MEM
;
2090 tpriv
->num_urbs
= 1;
2091 tpriv
->reap_action
= NORMAL
;
2093 urb
->usercontext
= itransfer
;
2094 urb
->type
= USBFS_URB_TYPE_CONTROL
;
2095 urb
->endpoint
= transfer
->endpoint
;
2096 urb
->buffer
= transfer
->buffer
;
2097 urb
->buffer_length
= transfer
->length
;
2099 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
2103 if (errno
== ENODEV
)
2104 return LIBUSB_ERROR_NO_DEVICE
;
2106 usbi_err(TRANSFER_CTX(transfer
),
2107 "submiturb failed error %d errno=%d", r
, errno
);
2108 return LIBUSB_ERROR_IO
;
2113 static int op_submit_transfer(struct usbi_transfer
*itransfer
)
2115 struct libusb_transfer
*transfer
=
2116 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2118 switch (transfer
->type
) {
2119 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2120 return submit_control_transfer(itransfer
);
2121 case LIBUSB_TRANSFER_TYPE_BULK
:
2122 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_BULK
);
2123 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2124 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_INTERRUPT
);
2125 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2126 return submit_iso_transfer(itransfer
);
2128 usbi_err(TRANSFER_CTX(transfer
),
2129 "unknown endpoint type %d", transfer
->type
);
2130 return LIBUSB_ERROR_INVALID_PARAM
;
2134 static int op_cancel_transfer(struct usbi_transfer
*itransfer
)
2136 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2137 struct libusb_transfer
*transfer
=
2138 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2140 switch (transfer
->type
) {
2141 case LIBUSB_TRANSFER_TYPE_BULK
:
2142 if (tpriv
->reap_action
== ERROR
)
2144 /* else, fall through */
2145 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2146 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2147 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2148 tpriv
->reap_action
= CANCELLED
;
2151 usbi_err(TRANSFER_CTX(transfer
),
2152 "unknown endpoint type %d", transfer
->type
);
2153 return LIBUSB_ERROR_INVALID_PARAM
;
2157 return LIBUSB_ERROR_NOT_FOUND
;
2159 return discard_urbs(itransfer
, 0, tpriv
->num_urbs
);
2162 static void op_clear_transfer_priv(struct usbi_transfer
*itransfer
)
2164 struct libusb_transfer
*transfer
=
2165 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2166 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2168 /* urbs can be freed also in submit_transfer so lock mutex first */
2169 switch (transfer
->type
) {
2170 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2171 case LIBUSB_TRANSFER_TYPE_BULK
:
2172 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2173 usbi_mutex_lock(&itransfer
->lock
);
2177 usbi_mutex_unlock(&itransfer
->lock
);
2179 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2180 usbi_mutex_lock(&itransfer
->lock
);
2181 if (tpriv
->iso_urbs
)
2182 free_iso_urbs(tpriv
);
2183 usbi_mutex_unlock(&itransfer
->lock
);
2186 usbi_err(TRANSFER_CTX(transfer
),
2187 "unknown endpoint type %d", transfer
->type
);
2191 static int handle_bulk_completion(struct usbi_transfer
*itransfer
,
2192 struct usbfs_urb
*urb
)
2194 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2195 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2196 int urb_idx
= urb
- tpriv
->urbs
;
2198 usbi_mutex_lock(&itransfer
->lock
);
2199 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb
->status
,
2200 urb_idx
+ 1, tpriv
->num_urbs
);
2202 tpriv
->num_retired
++;
2204 if (tpriv
->reap_action
!= NORMAL
) {
2205 /* cancelled, submit_fail, or completed early */
2206 usbi_dbg("abnormal reap: urb status %d", urb
->status
);
2208 /* even though we're in the process of cancelling, it's possible that
2209 * we may receive some data in these URBs that we don't want to lose.
2211 * 1. while the kernel is cancelling all the packets that make up an
2212 * URB, a few of them might complete. so we get back a successful
2213 * cancellation *and* some data.
2214 * 2. we receive a short URB which marks the early completion condition,
2215 * so we start cancelling the remaining URBs. however, we're too
2216 * slow and another URB completes (or at least completes partially).
2217 * (this can't happen since we always use BULK_CONTINUATION.)
2219 * When this happens, our objectives are not to lose any "surplus" data,
2220 * and also to stick it at the end of the previously-received data
2221 * (closing any holes), so that libusbx reports the total amount of
2222 * transferred data and presents it in a contiguous chunk.
2224 if (urb
->actual_length
> 0) {
2225 unsigned char *target
= transfer
->buffer
+ itransfer
->transferred
;
2226 usbi_dbg("received %d bytes of surplus data", urb
->actual_length
);
2227 if (urb
->buffer
!= target
) {
2228 usbi_dbg("moving surplus data from offset %d to offset %d",
2229 (unsigned char *) urb
->buffer
- transfer
->buffer
,
2230 target
- transfer
->buffer
);
2231 memmove(target
, urb
->buffer
, urb
->actual_length
);
2233 itransfer
->transferred
+= urb
->actual_length
;
2236 if (tpriv
->num_retired
== tpriv
->num_urbs
) {
2237 usbi_dbg("abnormal reap: last URB handled, reporting");
2238 if (tpriv
->reap_action
!= COMPLETED_EARLY
&&
2239 tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2240 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2246 itransfer
->transferred
+= urb
->actual_length
;
2248 /* Many of these errors can occur on *any* urb of a multi-urb
2249 * transfer. When they do, we tear down the rest of the transfer.
2251 switch (urb
->status
) {
2254 case -EREMOTEIO
: /* short transfer */
2256 case -ENOENT
: /* cancelled */
2261 usbi_dbg("device removed");
2262 tpriv
->reap_status
= LIBUSB_TRANSFER_NO_DEVICE
;
2263 goto cancel_remaining
;
2265 usbi_dbg("detected endpoint stall");
2266 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2267 tpriv
->reap_status
= LIBUSB_TRANSFER_STALL
;
2268 goto cancel_remaining
;
2270 /* overflow can only ever occur in the last urb */
2271 usbi_dbg("overflow, actual_length=%d", urb
->actual_length
);
2272 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2273 tpriv
->reap_status
= LIBUSB_TRANSFER_OVERFLOW
;
2280 usbi_dbg("low level error %d", urb
->status
);
2281 tpriv
->reap_action
= ERROR
;
2282 goto cancel_remaining
;
2284 usbi_warn(ITRANSFER_CTX(itransfer
),
2285 "unrecognised urb status %d", urb
->status
);
2286 tpriv
->reap_action
= ERROR
;
2287 goto cancel_remaining
;
2290 /* if we're the last urb or we got less data than requested then we're
2292 if (urb_idx
== tpriv
->num_urbs
- 1) {
2293 usbi_dbg("last URB in transfer --> complete!");
2295 } else if (urb
->actual_length
< urb
->buffer_length
) {
2296 usbi_dbg("short transfer %d/%d --> complete!",
2297 urb
->actual_length
, urb
->buffer_length
);
2298 if (tpriv
->reap_action
== NORMAL
)
2299 tpriv
->reap_action
= COMPLETED_EARLY
;
2304 if (ERROR
== tpriv
->reap_action
&& LIBUSB_TRANSFER_COMPLETED
== tpriv
->reap_status
)
2305 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2307 if (tpriv
->num_retired
== tpriv
->num_urbs
) /* nothing to cancel */
2310 /* cancel remaining urbs and wait for their completion before
2311 * reporting results */
2312 discard_urbs(itransfer
, urb_idx
+ 1, tpriv
->num_urbs
);
2315 usbi_mutex_unlock(&itransfer
->lock
);
2321 usbi_mutex_unlock(&itransfer
->lock
);
2322 return CANCELLED
== tpriv
->reap_action
?
2323 usbi_handle_transfer_cancellation(itransfer
) :
2324 usbi_handle_transfer_completion(itransfer
, tpriv
->reap_status
);
2327 static int handle_iso_completion(struct usbi_transfer
*itransfer
,
2328 struct usbfs_urb
*urb
)
2330 struct libusb_transfer
*transfer
=
2331 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2332 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2333 int num_urbs
= tpriv
->num_urbs
;
2336 enum libusb_transfer_status status
= LIBUSB_TRANSFER_COMPLETED
;
2338 usbi_mutex_lock(&itransfer
->lock
);
2339 for (i
= 0; i
< num_urbs
; i
++) {
2340 if (urb
== tpriv
->iso_urbs
[i
]) {
2346 usbi_err(TRANSFER_CTX(transfer
), "could not locate urb!");
2347 usbi_mutex_unlock(&itransfer
->lock
);
2348 return LIBUSB_ERROR_NOT_FOUND
;
2351 usbi_dbg("handling completion status %d of iso urb %d/%d", urb
->status
,
2354 /* copy isochronous results back in */
2356 for (i
= 0; i
< urb
->number_of_packets
; i
++) {
2357 struct usbfs_iso_packet_desc
*urb_desc
= &urb
->iso_frame_desc
[i
];
2358 struct libusb_iso_packet_descriptor
*lib_desc
=
2359 &transfer
->iso_packet_desc
[tpriv
->iso_packet_offset
++];
2360 lib_desc
->status
= LIBUSB_TRANSFER_COMPLETED
;
2361 switch (urb_desc
->status
) {
2364 case -ENOENT
: /* cancelled */
2369 usbi_dbg("device removed");
2370 lib_desc
->status
= LIBUSB_TRANSFER_NO_DEVICE
;
2373 usbi_dbg("detected endpoint stall");
2374 lib_desc
->status
= LIBUSB_TRANSFER_STALL
;
2377 usbi_dbg("overflow error");
2378 lib_desc
->status
= LIBUSB_TRANSFER_OVERFLOW
;
2386 usbi_dbg("low-level USB error %d", urb_desc
->status
);
2387 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2390 usbi_warn(TRANSFER_CTX(transfer
),
2391 "unrecognised urb status %d", urb_desc
->status
);
2392 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2395 lib_desc
->actual_length
= urb_desc
->actual_length
;
2398 tpriv
->num_retired
++;
2400 if (tpriv
->reap_action
!= NORMAL
) { /* cancelled or submit_fail */
2401 usbi_dbg("CANCEL: urb status %d", urb
->status
);
2403 if (tpriv
->num_retired
== num_urbs
) {
2404 usbi_dbg("CANCEL: last URB handled, reporting");
2405 free_iso_urbs(tpriv
);
2406 if (tpriv
->reap_action
== CANCELLED
) {
2407 usbi_mutex_unlock(&itransfer
->lock
);
2408 return usbi_handle_transfer_cancellation(itransfer
);
2410 usbi_mutex_unlock(&itransfer
->lock
);
2411 return usbi_handle_transfer_completion(itransfer
,
2412 LIBUSB_TRANSFER_ERROR
);
2418 switch (urb
->status
) {
2421 case -ENOENT
: /* cancelled */
2425 usbi_dbg("device removed");
2426 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2429 usbi_warn(TRANSFER_CTX(transfer
),
2430 "unrecognised urb status %d", urb
->status
);
2431 status
= LIBUSB_TRANSFER_ERROR
;
2435 /* if we're the last urb then we're done */
2436 if (urb_idx
== num_urbs
) {
2437 usbi_dbg("last URB in transfer --> complete!");
2438 free_iso_urbs(tpriv
);
2439 usbi_mutex_unlock(&itransfer
->lock
);
2440 return usbi_handle_transfer_completion(itransfer
, status
);
2444 usbi_mutex_unlock(&itransfer
->lock
);
2448 static int handle_control_completion(struct usbi_transfer
*itransfer
,
2449 struct usbfs_urb
*urb
)
2451 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2454 usbi_mutex_lock(&itransfer
->lock
);
2455 usbi_dbg("handling completion status %d", urb
->status
);
2457 itransfer
->transferred
+= urb
->actual_length
;
2459 if (tpriv
->reap_action
== CANCELLED
) {
2460 if (urb
->status
!= 0 && urb
->status
!= -ENOENT
)
2461 usbi_warn(ITRANSFER_CTX(itransfer
),
2462 "cancel: unrecognised urb status %d", urb
->status
);
2465 usbi_mutex_unlock(&itransfer
->lock
);
2466 return usbi_handle_transfer_cancellation(itransfer
);
2469 switch (urb
->status
) {
2471 status
= LIBUSB_TRANSFER_COMPLETED
;
2473 case -ENOENT
: /* cancelled */
2474 status
= LIBUSB_TRANSFER_CANCELLED
;
2478 usbi_dbg("device removed");
2479 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2482 usbi_dbg("unsupported control request");
2483 status
= LIBUSB_TRANSFER_STALL
;
2486 usbi_dbg("control overflow error");
2487 status
= LIBUSB_TRANSFER_OVERFLOW
;
2494 usbi_dbg("low-level bus error occurred");
2495 status
= LIBUSB_TRANSFER_ERROR
;
2498 usbi_warn(ITRANSFER_CTX(itransfer
),
2499 "unrecognised urb status %d", urb
->status
);
2500 status
= LIBUSB_TRANSFER_ERROR
;
2506 usbi_mutex_unlock(&itransfer
->lock
);
2507 return usbi_handle_transfer_completion(itransfer
, status
);
2510 static int reap_for_handle(struct libusb_device_handle
*handle
)
2512 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
2514 struct usbfs_urb
*urb
;
2515 struct usbi_transfer
*itransfer
;
2516 struct libusb_transfer
*transfer
;
2518 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_REAPURBNDELAY
, &urb
);
2519 if (r
== -1 && errno
== EAGAIN
)
2522 if (errno
== ENODEV
)
2523 return LIBUSB_ERROR_NO_DEVICE
;
2525 usbi_err(HANDLE_CTX(handle
), "reap failed error %d errno=%d",
2527 return LIBUSB_ERROR_IO
;
2530 itransfer
= urb
->usercontext
;
2531 transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2533 usbi_dbg("urb type=%d status=%d transferred=%d", urb
->type
, urb
->status
,
2534 urb
->actual_length
);
2536 switch (transfer
->type
) {
2537 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2538 return handle_iso_completion(itransfer
, urb
);
2539 case LIBUSB_TRANSFER_TYPE_BULK
:
2540 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2541 return handle_bulk_completion(itransfer
, urb
);
2542 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2543 return handle_control_completion(itransfer
, urb
);
2545 usbi_err(HANDLE_CTX(handle
), "unrecognised endpoint type %x",
2547 return LIBUSB_ERROR_OTHER
;
2551 static int op_handle_events(struct libusb_context
*ctx
,
2552 struct pollfd
*fds
, POLL_NFDS_TYPE nfds
, int num_ready
)
2557 usbi_mutex_lock(&ctx
->open_devs_lock
);
2558 for (i
= 0; i
< nfds
&& num_ready
> 0; i
++) {
2559 struct pollfd
*pollfd
= &fds
[i
];
2560 struct libusb_device_handle
*handle
;
2561 struct linux_device_handle_priv
*hpriv
= NULL
;
2563 if (!pollfd
->revents
)
2567 list_for_each_entry(handle
, &ctx
->open_devs
, list
, struct libusb_device_handle
) {
2568 hpriv
= _device_handle_priv(handle
);
2569 if (hpriv
->fd
== pollfd
->fd
)
2573 if (pollfd
->revents
& POLLERR
) {
2574 usbi_remove_pollfd(HANDLE_CTX(handle
), hpriv
->fd
);
2575 usbi_handle_disconnect(handle
);
2580 r
= reap_for_handle(handle
);
2582 if (r
== 1 || r
== LIBUSB_ERROR_NO_DEVICE
)
2590 usbi_mutex_unlock(&ctx
->open_devs_lock
);
2594 static int op_clock_gettime(int clk_id
, struct timespec
*tp
)
2597 case USBI_CLOCK_MONOTONIC
:
2598 return clock_gettime(monotonic_clkid
, tp
);
2599 case USBI_CLOCK_REALTIME
:
2600 return clock_gettime(CLOCK_REALTIME
, tp
);
2602 return LIBUSB_ERROR_INVALID_PARAM
;
2606 #ifdef USBI_TIMERFD_AVAILABLE
2607 static clockid_t
op_get_timerfd_clockid(void)
2609 return monotonic_clkid
;
2614 const struct usbi_os_backend linux_usbfs_backend
= {
2615 .name
= "Linux usbfs",
2616 .caps
= USBI_CAP_HAS_HID_ACCESS
|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
,
2619 .get_device_list
= NULL
,
2620 .get_device_descriptor
= op_get_device_descriptor
,
2621 .get_active_config_descriptor
= op_get_active_config_descriptor
,
2622 .get_config_descriptor
= op_get_config_descriptor
,
2626 .get_configuration
= op_get_configuration
,
2627 .set_configuration
= op_set_configuration
,
2628 .claim_interface
= op_claim_interface
,
2629 .release_interface
= op_release_interface
,
2631 .set_interface_altsetting
= op_set_interface
,
2632 .clear_halt
= op_clear_halt
,
2633 .reset_device
= op_reset_device
,
2635 .kernel_driver_active
= op_kernel_driver_active
,
2636 .detach_kernel_driver
= op_detach_kernel_driver
,
2637 .attach_kernel_driver
= op_attach_kernel_driver
,
2639 .destroy_device
= op_destroy_device
,
2641 .submit_transfer
= op_submit_transfer
,
2642 .cancel_transfer
= op_cancel_transfer
,
2643 .clear_transfer_priv
= op_clear_transfer_priv
,
2645 .handle_events
= op_handle_events
,
2647 .clock_gettime
= op_clock_gettime
,
2649 #ifdef USBI_TIMERFD_AVAILABLE
2650 .get_timerfd_clockid
= op_get_timerfd_clockid
,
2653 .device_priv_size
= sizeof(struct linux_device_priv
),
2654 .device_handle_priv_size
= sizeof(struct linux_device_handle_priv
),
2655 .transfer_priv_size
= sizeof(struct linux_transfer_priv
),
2656 .add_iso_packet_size
= 0,