2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <sys/ioctl.h>
32 #include <sys/types.h>
33 #include <sys/utsname.h>
38 #include "linux_usbfs.h"
41 * opening a usbfs node causes the device to be resumed, so we attempt to
42 * avoid this during enumeration.
44 * sysfs allows us to read the kernel's in-memory copies of device descriptors
45 * and so forth, avoiding the need to open the device:
46 * - The binary "descriptors" file was added in 2.6.23.
47 * - The "busnum" file was added in 2.6.22
48 * - The "devnum" file has been present since pre-2.6.18
49 * - the "bConfigurationValue" file has been present since pre-2.6.18
51 * If we have bConfigurationValue, busnum, and devnum, then we can determine
52 * the active configuration without having to open the usbfs node in RDWR mode.
53 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
54 * The busnum file is important as that is the only way we can relate sysfs
55 * devices to usbfs nodes.
57 * If we also have descriptors, we can obtain the device descriptor and active
58 * configuration without touching usbfs at all.
60 * The descriptors file originally only contained the active configuration
61 * descriptor alongside the device descriptor, but all configurations are
62 * included as of Linux 2.6.26.
65 /* endianness for multi-byte fields:
67 * Descriptors exposed by usbfs have the multi-byte fields in the device
68 * descriptor as host endian. Multi-byte fields in the other descriptors are
69 * bus-endian. The kernel documentation says otherwise, but it is wrong.
72 static const char *usbfs_path
= NULL
;
74 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
75 static int usbdev_names
= 0;
77 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
78 * allows us to mark URBs as being part of a specific logical transfer when
79 * we submit them to the kernel. then, on any error except a cancellation, all
80 * URBs within that transfer will be cancelled and no more URBs will be
81 * accepted for the transfer, meaning that no more data can creep in.
83 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
84 * (in either direction) except the first.
85 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
86 * last; it means that the kernel should treat a short reply as an error.
87 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
88 * transfers can't be short unless there's already some sort of error), and
89 * setting this flag is disallowed (a kernel with USB debugging enabled will
92 static int supports_flag_bulk_continuation
= -1;
94 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
95 * allows us to mark URBs that should be followed by a zero length data
96 * packet, which can be required by device- or class-specific protocols.
98 static int supports_flag_zero_packet
= -1;
100 /* clock ID for monotonic clock, as not all clock sources are available on all
101 * systems. appropriate choice made at initialization time. */
102 static clockid_t monotonic_clkid
= -1;
104 /* do we have a busnum to relate devices? this also implies that we can read
105 * the active configuration through bConfigurationValue */
106 static int sysfs_can_relate_devices
= 0;
108 /* do we have a descriptors file? */
109 static int sysfs_has_descriptors
= 0;
111 struct linux_device_priv
{
113 unsigned char *dev_descriptor
;
114 unsigned char *config_descriptor
;
117 struct linux_device_handle_priv
{
124 /* submission failed after the first URB, so await cancellation/completion
125 * of all the others */
128 /* cancelled by user or timeout */
131 /* completed multi-URB transfer in non-final URB */
134 /* one or more urbs encountered a low-level error */
138 struct linux_transfer_priv
{
140 struct usbfs_urb
*urbs
;
141 struct usbfs_urb
**iso_urbs
;
144 enum reap_action reap_action
;
147 enum libusb_transfer_status reap_status
;
149 /* next iso packet in user-supplied transfer to be populated */
150 int iso_packet_offset
;
153 static void _get_usbfs_path(struct libusb_device
*dev
, char *path
)
156 snprintf(path
, PATH_MAX
, "%s/usbdev%d.%d",
157 usbfs_path
, dev
->bus_number
, dev
->device_address
);
159 snprintf(path
, PATH_MAX
, "%s/%03d/%03d",
160 usbfs_path
, dev
->bus_number
, dev
->device_address
);
163 static struct linux_device_priv
*_device_priv(struct libusb_device
*dev
)
165 return (struct linux_device_priv
*) dev
->os_priv
;
168 static struct linux_device_handle_priv
*_device_handle_priv(
169 struct libusb_device_handle
*handle
)
171 return (struct linux_device_handle_priv
*) handle
->os_priv
;
174 /* check dirent for a /dev/usbdev%d.%d name
175 * optionally return bus/device on success */
176 static int _is_usbdev_entry(struct dirent
*entry
, int *bus_p
, int *dev_p
)
180 if (sscanf(entry
->d_name
, "usbdev%d.%d", &busnum
, &devnum
) != 2)
183 usbi_dbg("found: %s", entry
->d_name
);
191 static int check_usb_vfs(const char *dirname
)
194 struct dirent
*entry
;
197 dir
= opendir(dirname
);
201 while ((entry
= readdir(dir
)) != NULL
) {
202 if (entry
->d_name
[0] == '.')
205 /* We assume if we find any files that it must be the right place */
214 static const char *find_usbfs_path(void)
216 const char *path
= "/dev/bus/usb";
217 const char *ret
= NULL
;
219 if (check_usb_vfs(path
)) {
222 path
= "/proc/bus/usb";
223 if (check_usb_vfs(path
))
227 /* look for /dev/usbdev*.* if the normal places fail */
229 struct dirent
*entry
;
235 while ((entry
= readdir(dir
)) != NULL
) {
236 if (_is_usbdev_entry(entry
, NULL
, NULL
)) {
237 /* found one; that's enough */
248 usbi_dbg("found usbfs at %s", ret
);
253 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
254 * seem to lack it). fall back to REALTIME if we have to. */
255 static clockid_t
find_monotonic_clock(void)
257 #ifdef CLOCK_MONOTONIC
261 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
262 * because it's not available through timerfd */
263 r
= clock_gettime(CLOCK_MONOTONIC
, &ts
);
265 return CLOCK_MONOTONIC
;
266 usbi_dbg("monotonic clock doesn't work, errno %d", errno
);
269 return CLOCK_REALTIME
;
272 static int kernel_version_ge(int major
, int minor
, int sublevel
)
275 int atoms
, kmajor
, kminor
, ksublevel
;
279 atoms
= sscanf(uts
.release
, "%d.%d.%d", &kmajor
, &kminor
, &ksublevel
);
288 /* kmajor == major */
290 return 0 == minor
&& 0 == sublevel
;
296 /* kminor == minor */
298 return 0 == sublevel
;
300 return ksublevel
>= sublevel
;
303 /* Return 1 if filename exists inside dirname in sysfs.
304 SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
305 static int sysfs_has_file(const char *dirname
, const char *filename
)
311 snprintf(path
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
, dirname
, filename
);
312 r
= stat(path
, &statbuf
);
313 if (r
== 0 && S_ISREG(statbuf
.st_mode
))
319 static int op_init(struct libusb_context
*ctx
)
324 usbfs_path
= find_usbfs_path();
326 usbi_err(ctx
, "could not find usbfs");
327 return LIBUSB_ERROR_OTHER
;
330 if (monotonic_clkid
== -1)
331 monotonic_clkid
= find_monotonic_clock();
333 if (supports_flag_bulk_continuation
== -1) {
334 /* bulk continuation URB flag available from Linux 2.6.32 */
335 supports_flag_bulk_continuation
= kernel_version_ge(2,6,32);
336 if (supports_flag_bulk_continuation
== -1) {
337 usbi_err(ctx
, "error checking for bulk continuation support");
338 return LIBUSB_ERROR_OTHER
;
342 if (supports_flag_bulk_continuation
)
343 usbi_dbg("bulk continuation flag supported");
345 if (-1 == supports_flag_zero_packet
) {
346 /* zero length packet URB flag fixed since Linux 2.6.31 */
347 supports_flag_zero_packet
= kernel_version_ge(2,6,31);
348 if (-1 == supports_flag_zero_packet
) {
349 usbi_err(ctx
, "error checking for zero length packet support");
350 return LIBUSB_ERROR_OTHER
;
354 if (supports_flag_zero_packet
)
355 usbi_dbg("zero length packet flag supported");
357 r
= stat(SYSFS_DEVICE_PATH
, &statbuf
);
358 if (r
== 0 && S_ISDIR(statbuf
.st_mode
)) {
359 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
360 struct dirent
*entry
;
362 usbi_dbg("found usb devices in sysfs");
365 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
366 return LIBUSB_ERROR_IO
;
369 /* Make sure sysfs supports all the required files. If it
370 * does not, then usbfs will be used instead. Determine
371 * this by looping through the directories in
372 * SYSFS_DEVICE_PATH. With the assumption that there will
373 * always be subdirectories of the name usbN (usb1, usb2,
374 * etc) representing the root hubs, check the usbN
375 * subdirectories to see if they have all the needed files.
376 * This algorithm uses the usbN subdirectories (root hubs)
377 * because a device disconnection will cause a race
378 * condition regarding which files are available, sometimes
379 * causing an incorrect result. The root hubs are used
380 * because it is assumed that they will always be present.
381 * See the "sysfs vs usbfs" comment at the top of this file
382 * for more details. */
383 while ((entry
= readdir(devices
))) {
384 int has_busnum
=0, has_devnum
=0, has_descriptors
=0;
385 int has_configuration_value
=0;
387 /* Only check the usbN directories. */
388 if (strncmp(entry
->d_name
, "usb", 3) != 0)
391 /* Check for the files libusbx needs from sysfs. */
392 has_busnum
= sysfs_has_file(entry
->d_name
, "busnum");
393 has_devnum
= sysfs_has_file(entry
->d_name
, "devnum");
394 has_descriptors
= sysfs_has_file(entry
->d_name
, "descriptors");
395 has_configuration_value
= sysfs_has_file(entry
->d_name
, "bConfigurationValue");
397 if (has_busnum
&& has_devnum
&& has_configuration_value
)
398 sysfs_can_relate_devices
= 1;
400 sysfs_has_descriptors
= 1;
402 /* Only need to check until we've found ONE device which
403 has all the attributes. */
404 if (sysfs_has_descriptors
&& sysfs_can_relate_devices
)
409 /* Only use sysfs descriptors if the rest of
410 sysfs will work for libusb. */
411 if (!sysfs_can_relate_devices
)
412 sysfs_has_descriptors
= 0;
414 usbi_dbg("sysfs usb info not available");
415 sysfs_has_descriptors
= 0;
416 sysfs_can_relate_devices
= 0;
422 static int usbfs_get_device_descriptor(struct libusb_device
*dev
,
423 unsigned char *buffer
)
425 struct linux_device_priv
*priv
= _device_priv(dev
);
427 /* return cached copy */
428 memcpy(buffer
, priv
->dev_descriptor
, DEVICE_DESC_LENGTH
);
432 static int _open_sysfs_attr(struct libusb_device
*dev
, const char *attr
)
434 struct linux_device_priv
*priv
= _device_priv(dev
);
435 char filename
[PATH_MAX
];
438 snprintf(filename
, PATH_MAX
, "%s/%s/%s",
439 SYSFS_DEVICE_PATH
, priv
->sysfs_dir
, attr
);
440 fd
= open(filename
, O_RDONLY
);
442 usbi_err(DEVICE_CTX(dev
),
443 "open %s failed ret=%d errno=%d", filename
, fd
, errno
);
444 return LIBUSB_ERROR_IO
;
450 /* Note only suitable for attributes which always read >= 0, < 0 is error */
451 static int __read_sysfs_attr(struct libusb_context
*ctx
,
452 const char *devname
, const char *attr
)
454 char filename
[PATH_MAX
];
458 snprintf(filename
, PATH_MAX
, "%s/%s/%s", SYSFS_DEVICE_PATH
,
460 f
= fopen(filename
, "r");
462 if (errno
== ENOENT
) {
463 /* File doesn't exist. Assume the device has been
464 disconnected (see trac ticket #70). */
465 return LIBUSB_ERROR_NO_DEVICE
;
467 usbi_err(ctx
, "open %s failed errno=%d", filename
, errno
);
468 return LIBUSB_ERROR_IO
;
471 r
= fscanf(f
, "%d", &value
);
474 usbi_err(ctx
, "fscanf %s returned %d, errno=%d", attr
, r
, errno
);
475 return LIBUSB_ERROR_NO_DEVICE
; /* For unplug race (trac #70) */
478 usbi_err(ctx
, "%s contains a negative value", filename
);
479 return LIBUSB_ERROR_IO
;
485 static int sysfs_get_device_descriptor(struct libusb_device
*dev
,
486 unsigned char *buffer
)
491 /* sysfs provides access to an in-memory copy of the device descriptor,
492 * so we use that rather than keeping our own copy */
494 fd
= _open_sysfs_attr(dev
, "descriptors");
498 r
= read(fd
, buffer
, DEVICE_DESC_LENGTH
);;
501 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d", fd
, errno
);
502 return LIBUSB_ERROR_IO
;
503 } else if (r
< DEVICE_DESC_LENGTH
) {
504 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, DEVICE_DESC_LENGTH
);
505 return LIBUSB_ERROR_IO
;
511 static int op_get_device_descriptor(struct libusb_device
*dev
,
512 unsigned char *buffer
, int *host_endian
)
514 if (sysfs_has_descriptors
) {
515 return sysfs_get_device_descriptor(dev
, buffer
);
518 return usbfs_get_device_descriptor(dev
, buffer
);
522 static int usbfs_get_active_config_descriptor(struct libusb_device
*dev
,
523 unsigned char *buffer
, size_t len
)
525 struct linux_device_priv
*priv
= _device_priv(dev
);
526 if (!priv
->config_descriptor
)
527 return LIBUSB_ERROR_NOT_FOUND
; /* device is unconfigured */
529 /* retrieve cached copy */
530 memcpy(buffer
, priv
->config_descriptor
, len
);
534 /* read the bConfigurationValue for a device */
535 static int sysfs_get_active_config(struct libusb_device
*dev
, int *config
)
538 char tmp
[4] = {0, 0, 0, 0};
543 fd
= _open_sysfs_attr(dev
, "bConfigurationValue");
547 r
= read(fd
, tmp
, sizeof(tmp
));
550 usbi_err(DEVICE_CTX(dev
),
551 "read bConfigurationValue failed ret=%d errno=%d", r
, errno
);
552 return LIBUSB_ERROR_IO
;
554 usbi_dbg("device unconfigured");
559 if (tmp
[sizeof(tmp
) - 1] != 0) {
560 usbi_err(DEVICE_CTX(dev
), "not null-terminated?");
561 return LIBUSB_ERROR_IO
;
562 } else if (tmp
[0] == 0) {
563 usbi_err(DEVICE_CTX(dev
), "no configuration value?");
564 return LIBUSB_ERROR_IO
;
567 num
= strtol(tmp
, &endptr
, 10);
569 usbi_err(DEVICE_CTX(dev
), "error converting '%s' to integer", tmp
);
570 return LIBUSB_ERROR_IO
;
577 /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
578 * seeks to the next one. */
579 static int seek_to_next_config(struct libusb_context
*ctx
, int fd
,
582 struct libusb_config_descriptor config
;
583 unsigned char tmp
[6];
587 /* read first 6 bytes of descriptor */
588 r
= read(fd
, tmp
, sizeof(tmp
));
590 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
591 return LIBUSB_ERROR_IO
;
592 } else if (r
< sizeof(tmp
)) {
593 usbi_err(ctx
, "short descriptor read %d/%d", r
, sizeof(tmp
));
594 return LIBUSB_ERROR_IO
;
597 /* seek forward to end of config */
598 usbi_parse_descriptor(tmp
, "bbwbb", &config
, host_endian
);
599 off
= lseek(fd
, config
.wTotalLength
- sizeof(tmp
), SEEK_CUR
);
601 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
602 return LIBUSB_ERROR_IO
;
608 static int sysfs_get_active_config_descriptor(struct libusb_device
*dev
,
609 unsigned char *buffer
, size_t len
)
616 unsigned char tmp
[6];
618 r
= sysfs_get_active_config(dev
, &config
);
622 return LIBUSB_ERROR_NOT_FOUND
;
624 usbi_dbg("active configuration %d", config
);
626 /* sysfs provides access to an in-memory copy of the device descriptor,
627 * so we use that rather than keeping our own copy */
629 fd
= _open_sysfs_attr(dev
, "descriptors");
633 /* device might have been unconfigured since we read bConfigurationValue,
634 * so first check that there is any config descriptor data at all... */
635 off
= lseek(fd
, 0, SEEK_END
);
637 usbi_err(DEVICE_CTX(dev
), "end seek failed, ret=%d errno=%d",
640 return LIBUSB_ERROR_IO
;
641 } else if (off
== DEVICE_DESC_LENGTH
) {
643 return LIBUSB_ERROR_NOT_FOUND
;
646 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
648 usbi_err(DEVICE_CTX(dev
), "seek failed, ret=%d errno=%d", off
, errno
);
650 return LIBUSB_ERROR_IO
;
653 /* unbounded loop: we expect the descriptor to be present under all
656 r
= read(fd
, tmp
, sizeof(tmp
));
658 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
660 return LIBUSB_ERROR_IO
;
661 } else if (r
< sizeof(tmp
)) {
662 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, sizeof(tmp
));
663 return LIBUSB_ERROR_IO
;
666 /* check bConfigurationValue */
667 if (tmp
[5] == config
)
670 /* try the next descriptor */
671 off
= lseek(fd
, 0 - sizeof(tmp
), SEEK_CUR
);
673 return LIBUSB_ERROR_IO
;
675 r
= seek_to_next_config(DEVICE_CTX(dev
), fd
, 0);
680 to_copy
= (len
< sizeof(tmp
)) ? len
: sizeof(tmp
);
681 memcpy(buffer
, tmp
, to_copy
);
682 if (len
> sizeof(tmp
)) {
683 r
= read(fd
, buffer
+ sizeof(tmp
), len
- sizeof(tmp
));
685 usbi_err(DEVICE_CTX(dev
), "read failed, ret=%d errno=%d",
689 usbi_dbg("device is unconfigured");
690 r
= LIBUSB_ERROR_NOT_FOUND
;
691 } else if (r
< len
- sizeof(tmp
)) {
692 usbi_err(DEVICE_CTX(dev
), "short read %d/%d", r
, len
);
703 static int op_get_active_config_descriptor(struct libusb_device
*dev
,
704 unsigned char *buffer
, size_t len
, int *host_endian
)
706 if (sysfs_has_descriptors
) {
707 return sysfs_get_active_config_descriptor(dev
, buffer
, len
);
709 return usbfs_get_active_config_descriptor(dev
, buffer
, len
);
713 /* takes a usbfs fd, attempts to find the requested config and copy a certain
714 * amount of it into an output buffer. */
715 static int get_config_descriptor(struct libusb_context
*ctx
, int fd
,
716 uint8_t config_index
, unsigned char *buffer
, size_t len
)
721 off
= lseek(fd
, DEVICE_DESC_LENGTH
, SEEK_SET
);
723 usbi_err(ctx
, "seek failed ret=%d errno=%d", off
, errno
);
724 return LIBUSB_ERROR_IO
;
727 /* might need to skip some configuration descriptors to reach the
728 * requested configuration */
729 while (config_index
> 0) {
730 r
= seek_to_next_config(ctx
, fd
, 1);
736 /* read the rest of the descriptor */
737 r
= read(fd
, buffer
, len
);
739 usbi_err(ctx
, "read failed ret=%d errno=%d", r
, errno
);
740 return LIBUSB_ERROR_IO
;
741 } else if (r
< len
) {
742 usbi_err(ctx
, "short output read %d/%d", r
, len
);
748 static int op_get_config_descriptor(struct libusb_device
*dev
,
749 uint8_t config_index
, unsigned char *buffer
, size_t len
, int *host_endian
)
751 char filename
[PATH_MAX
];
755 /* always read from usbfs: sysfs only has the active descriptor
756 * this will involve waking the device up, but oh well! */
758 /* FIXME: the above is no longer true, new kernels have all descriptors
759 * in the descriptors file. but its kinda hard to detect if the kernel
760 * is sufficiently new. */
762 _get_usbfs_path(dev
, filename
);
763 fd
= open(filename
, O_RDONLY
);
765 usbi_err(DEVICE_CTX(dev
),
766 "open '%s' failed, ret=%d errno=%d", filename
, fd
, errno
);
767 return LIBUSB_ERROR_IO
;
770 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, config_index
, buffer
, len
);
775 /* cache the active config descriptor in memory. a value of -1 means that
776 * we aren't sure which one is active, so just assume the first one.
778 static int cache_active_config(struct libusb_device
*dev
, int fd
,
781 struct linux_device_priv
*priv
= _device_priv(dev
);
782 struct libusb_config_descriptor config
;
783 unsigned char tmp
[8];
788 if (active_config
== -1) {
791 r
= usbi_get_config_index_by_value(dev
, active_config
, &idx
);
795 return LIBUSB_ERROR_NOT_FOUND
;
798 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, tmp
, sizeof(tmp
));
800 usbi_err(DEVICE_CTX(dev
), "first read error %d", r
);
804 usbi_parse_descriptor(tmp
, "bbw", &config
, 0);
805 buf
= malloc(config
.wTotalLength
);
807 return LIBUSB_ERROR_NO_MEM
;
809 r
= get_config_descriptor(DEVICE_CTX(dev
), fd
, idx
, buf
,
810 config
.wTotalLength
);
816 if (priv
->config_descriptor
)
817 free(priv
->config_descriptor
);
818 priv
->config_descriptor
= buf
;
822 /* send a control message to retrieve active configuration */
823 static int usbfs_get_active_config(struct libusb_device
*dev
, int fd
)
825 unsigned char active_config
= 0;
828 struct usbfs_ctrltransfer ctrl
= {
829 .bmRequestType
= LIBUSB_ENDPOINT_IN
,
830 .bRequest
= LIBUSB_REQUEST_GET_CONFIGURATION
,
835 .data
= &active_config
838 r
= ioctl(fd
, IOCTL_USBFS_CONTROL
, &ctrl
);
841 return LIBUSB_ERROR_NO_DEVICE
;
843 /* we hit this error path frequently with buggy devices :( */
844 usbi_warn(DEVICE_CTX(dev
),
845 "get_configuration failed ret=%d errno=%d", r
, errno
);
846 return LIBUSB_ERROR_IO
;
849 return active_config
;
852 static int initialize_device(struct libusb_device
*dev
, uint8_t busnum
,
853 uint8_t devaddr
, const char *sysfs_dir
)
855 struct linux_device_priv
*priv
= _device_priv(dev
);
856 unsigned char *dev_buf
;
859 int active_config
= 0;
860 int device_configured
= 1;
863 dev
->bus_number
= busnum
;
864 dev
->device_address
= devaddr
;
867 priv
->sysfs_dir
= malloc(strlen(sysfs_dir
) + 1);
868 if (!priv
->sysfs_dir
)
869 return LIBUSB_ERROR_NO_MEM
;
870 strcpy(priv
->sysfs_dir
, sysfs_dir
);
872 /* Note speed can contain 1.5, in this case __read_sysfs_attr
873 will stop parsing at the '.' and return 1 */
874 speed
= __read_sysfs_attr(DEVICE_CTX(dev
), sysfs_dir
, "speed");
877 case 1: dev
->speed
= LIBUSB_SPEED_LOW
; break;
878 case 12: dev
->speed
= LIBUSB_SPEED_FULL
; break;
879 case 480: dev
->speed
= LIBUSB_SPEED_HIGH
; break;
880 case 5000: dev
->speed
= LIBUSB_SPEED_SUPER
; break;
882 usbi_warn(DEVICE_CTX(dev
), "Unknown device speed: %d Mbps", speed
);
887 if (sysfs_has_descriptors
)
890 /* cache device descriptor in memory so that we can retrieve it later
891 * without waking the device up (op_get_device_descriptor) */
893 priv
->dev_descriptor
= NULL
;
894 priv
->config_descriptor
= NULL
;
896 if (sysfs_can_relate_devices
) {
897 int tmp
= sysfs_get_active_config(dev
, &active_config
);
900 if (active_config
== -1)
901 device_configured
= 0;
904 _get_usbfs_path(dev
, path
);
905 fd
= open(path
, O_RDWR
);
906 if (fd
< 0 && errno
== EACCES
) {
907 fd
= open(path
, O_RDONLY
);
908 /* if we only have read-only access to the device, we cannot
909 * send a control message to determine the active config. just
910 * assume the first one is active. */
915 usbi_err(DEVICE_CTX(dev
), "open failed, ret=%d errno=%d", fd
, errno
);
916 return LIBUSB_ERROR_IO
;
919 if (!sysfs_can_relate_devices
) {
920 if (active_config
== -1) {
921 /* if we only have read-only access to the device, we cannot
922 * send a control message to determine the active config. just
923 * assume the first one is active. */
924 usbi_warn(DEVICE_CTX(dev
), "access to %s is read-only; cannot "
925 "determine active configuration descriptor", path
);
927 active_config
= usbfs_get_active_config(dev
, fd
);
928 if (active_config
== LIBUSB_ERROR_IO
) {
929 /* buggy devices sometimes fail to report their active config.
930 * assume unconfigured and continue the probing */
931 usbi_warn(DEVICE_CTX(dev
), "couldn't query active "
932 "configuration, assumung unconfigured");
933 device_configured
= 0;
934 } else if (active_config
< 0) {
936 return active_config
;
937 } else if (active_config
== 0) {
938 /* some buggy devices have a configuration 0, but we're
939 * reaching into the corner of a corner case here, so let's
940 * not support buggy devices in these circumstances.
941 * stick to the specs: a configuration value of 0 means
943 usbi_dbg("active cfg 0? assuming unconfigured device");
944 device_configured
= 0;
949 dev_buf
= malloc(DEVICE_DESC_LENGTH
);
952 return LIBUSB_ERROR_NO_MEM
;
955 r
= read(fd
, dev_buf
, DEVICE_DESC_LENGTH
);
957 usbi_err(DEVICE_CTX(dev
),
958 "read descriptor failed ret=%d errno=%d", fd
, errno
);
961 return LIBUSB_ERROR_IO
;
962 } else if (r
< DEVICE_DESC_LENGTH
) {
963 usbi_err(DEVICE_CTX(dev
), "short descriptor read (%d)", r
);
966 return LIBUSB_ERROR_IO
;
969 /* bit of a hack: set num_configurations now because cache_active_config()
970 * calls usbi_get_config_index_by_value() which uses it */
971 dev
->num_configurations
= dev_buf
[DEVICE_DESC_LENGTH
- 1];
973 if (device_configured
) {
974 r
= cache_active_config(dev
, fd
, active_config
);
983 priv
->dev_descriptor
= dev_buf
;
987 static int enumerate_device(struct libusb_context
*ctx
,
988 struct discovered_devs
**_discdevs
, uint8_t busnum
, uint8_t devaddr
,
989 const char *sysfs_dir
)
991 struct discovered_devs
*discdevs
;
992 unsigned long session_id
;
994 struct libusb_device
*dev
;
997 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
998 * will be reused. instead we should add a simple sysfs attribute with
1000 session_id
= busnum
<< 8 | devaddr
;
1001 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum
, devaddr
,
1004 dev
= usbi_get_device_by_session_id(ctx
, session_id
);
1006 usbi_dbg("using existing device for %d/%d (session %ld)",
1007 busnum
, devaddr
, session_id
);
1009 usbi_dbg("allocating new device for %d/%d (session %ld)",
1010 busnum
, devaddr
, session_id
);
1011 dev
= usbi_alloc_device(ctx
, session_id
);
1013 return LIBUSB_ERROR_NO_MEM
;
1015 r
= initialize_device(dev
, busnum
, devaddr
, sysfs_dir
);
1018 r
= usbi_sanitize_device(dev
);
1023 discdevs
= discovered_devs_append(*_discdevs
, dev
);
1025 r
= LIBUSB_ERROR_NO_MEM
;
1027 *_discdevs
= discdevs
;
1031 libusb_unref_device(dev
);
1035 /* open a bus directory and adds all discovered devices to discdevs. on
1036 * failure (non-zero return) the pre-existing discdevs should be destroyed
1037 * (and devices freed). on success, the new discdevs pointer should be used
1038 * as it may have been moved. */
1039 static int usbfs_scan_busdir(struct libusb_context
*ctx
,
1040 struct discovered_devs
**_discdevs
, uint8_t busnum
)
1043 char dirpath
[PATH_MAX
];
1044 struct dirent
*entry
;
1045 struct discovered_devs
*discdevs
= *_discdevs
;
1046 int r
= LIBUSB_ERROR_IO
;
1048 snprintf(dirpath
, PATH_MAX
, "%s/%03d", usbfs_path
, busnum
);
1049 usbi_dbg("%s", dirpath
);
1050 dir
= opendir(dirpath
);
1052 usbi_err(ctx
, "opendir '%s' failed, errno=%d", dirpath
, errno
);
1053 /* FIXME: should handle valid race conditions like hub unplugged
1054 * during directory iteration - this is not an error */
1058 while ((entry
= readdir(dir
))) {
1061 if (entry
->d_name
[0] == '.')
1064 devaddr
= atoi(entry
->d_name
);
1066 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1070 if (enumerate_device(ctx
, &discdevs
, busnum
, (uint8_t) devaddr
, NULL
)) {
1071 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1079 *_discdevs
= discdevs
;
1084 static int usbfs_get_device_list(struct libusb_context
*ctx
,
1085 struct discovered_devs
**_discdevs
)
1087 struct dirent
*entry
;
1088 DIR *buses
= opendir(usbfs_path
);
1089 struct discovered_devs
*discdevs
= *_discdevs
;
1093 usbi_err(ctx
, "opendir buses failed errno=%d", errno
);
1094 return LIBUSB_ERROR_IO
;
1097 while ((entry
= readdir(buses
))) {
1098 struct discovered_devs
*discdevs_new
= discdevs
;
1101 if (entry
->d_name
[0] == '.')
1106 if (!_is_usbdev_entry(entry
, &busnum
, &devaddr
))
1109 r
= enumerate_device(ctx
, &discdevs_new
, busnum
,
1110 (uint8_t) devaddr
, NULL
);
1112 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1116 busnum
= atoi(entry
->d_name
);
1118 usbi_dbg("unknown dir entry %s", entry
->d_name
);
1122 r
= usbfs_scan_busdir(ctx
, &discdevs_new
, busnum
);
1126 discdevs
= discdevs_new
;
1131 *_discdevs
= discdevs
;
1136 static int sysfs_scan_device(struct libusb_context
*ctx
,
1137 struct discovered_devs
**_discdevs
, const char *devname
)
1142 usbi_dbg("scan %s", devname
);
1144 busnum
= __read_sysfs_attr(ctx
, devname
, "busnum");
1148 devaddr
= __read_sysfs_attr(ctx
, devname
, "devnum");
1152 usbi_dbg("bus=%d dev=%d", busnum
, devaddr
);
1153 if (busnum
> 255 || devaddr
> 255)
1154 return LIBUSB_ERROR_INVALID_PARAM
;
1156 return enumerate_device(ctx
, _discdevs
, busnum
& 0xff, devaddr
& 0xff,
1160 static void sysfs_analyze_topology(struct discovered_devs
*discdevs
)
1162 struct linux_device_priv
*priv
;
1164 struct libusb_device
*dev1
, *dev2
;
1165 const char *sysfs_dir1
, *sysfs_dir2
;
1167 int n
, boundary_char
;
1169 /* Fill in the port_number and parent_dev fields for each device */
1171 for (i
= 0; i
< discdevs
->len
; ++i
) {
1172 dev1
= discdevs
->devices
[i
];
1173 priv
= _device_priv(dev1
);
1176 sysfs_dir1
= priv
->sysfs_dir
;
1178 /* Root hubs have sysfs_dir names of the form "usbB",
1179 * where B is the bus number. All other devices have
1180 * sysfs_dir names of the form "B-P[.P ...]", where the
1181 * P values are port numbers leading from the root hub
1185 /* Root hubs don't have parents or port numbers */
1186 if (sysfs_dir1
[0] == 'u')
1189 /* The rightmost component is the device's port number */
1190 p
= strrchr(sysfs_dir1
, '.');
1192 p
= strchr(sysfs_dir1
, '-');
1194 continue; /* Should never happen */
1196 dev1
->port_number
= atoi(p
+ 1);
1198 /* Search for the parent device */
1201 for (j
= 0; j
< discdevs
->len
; ++j
) {
1202 dev2
= discdevs
->devices
[j
];
1203 priv
= _device_priv(dev2
);
1206 sysfs_dir2
= priv
->sysfs_dir
;
1208 if (boundary_char
== '-') {
1209 /* The parent's name must begin with 'usb';
1210 * skip past that part of sysfs_dir2.
1212 if (sysfs_dir2
[0] != 'u')
1217 /* The remainder of the parent's name must be equal to
1218 * the first n bytes of sysfs_dir1.
1220 if (memcmp(sysfs_dir1
, sysfs_dir2
, n
) == 0 && !sysfs_dir2
[n
]) {
1221 dev1
->parent_dev
= dev2
;
1228 static int sysfs_get_device_list(struct libusb_context
*ctx
,
1229 struct discovered_devs
**_discdevs
)
1231 struct discovered_devs
*discdevs
= *_discdevs
;
1232 DIR *devices
= opendir(SYSFS_DEVICE_PATH
);
1233 struct dirent
*entry
;
1234 int r
= LIBUSB_ERROR_IO
;
1237 usbi_err(ctx
, "opendir devices failed errno=%d", errno
);
1241 while ((entry
= readdir(devices
))) {
1242 struct discovered_devs
*discdevs_new
= discdevs
;
1244 if ((!isdigit(entry
->d_name
[0]) && strncmp(entry
->d_name
, "usb", 3))
1245 || strchr(entry
->d_name
, ':'))
1248 if (sysfs_scan_device(ctx
, &discdevs_new
, entry
->d_name
)) {
1249 usbi_dbg("failed to enumerate dir entry %s", entry
->d_name
);
1254 discdevs
= discdevs_new
;
1258 *_discdevs
= discdevs
;
1260 sysfs_analyze_topology(discdevs
);
1264 static int op_get_device_list(struct libusb_context
*ctx
,
1265 struct discovered_devs
**_discdevs
)
1267 /* we can retrieve device list and descriptors from sysfs or usbfs.
1268 * sysfs is preferable, because if we use usbfs we end up resuming
1269 * any autosuspended USB devices. however, sysfs is not available
1270 * everywhere, so we need a usbfs fallback too.
1272 * as described in the "sysfs vs usbfs" comment at the top of this
1273 * file, sometimes we have sysfs but not enough information to
1274 * relate sysfs devices to usbfs nodes. op_init() determines the
1275 * adequacy of sysfs and sets sysfs_can_relate_devices.
1277 if (sysfs_can_relate_devices
!= 0)
1278 return sysfs_get_device_list(ctx
, _discdevs
);
1280 return usbfs_get_device_list(ctx
, _discdevs
);
1283 static int op_open(struct libusb_device_handle
*handle
)
1285 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
1286 char filename
[PATH_MAX
];
1289 _get_usbfs_path(handle
->dev
, filename
);
1290 usbi_dbg("opening %s", filename
);
1291 hpriv
->fd
= open(filename
, O_RDWR
);
1292 if (hpriv
->fd
< 0) {
1293 if (errno
== EACCES
) {
1294 usbi_err(HANDLE_CTX(handle
), "libusbx couldn't open USB device %s: "
1295 "Permission denied.", filename
);
1296 usbi_err(HANDLE_CTX(handle
),
1297 "libusbx requires write access to USB device nodes.");
1298 return LIBUSB_ERROR_ACCESS
;
1299 } else if (errno
== ENOENT
) {
1300 usbi_err(HANDLE_CTX(handle
), "libusbx couldn't open USB device %s: "
1301 "No such file or directory.", filename
);
1302 return LIBUSB_ERROR_NO_DEVICE
;
1304 usbi_err(HANDLE_CTX(handle
),
1305 "open failed, code %d errno %d", hpriv
->fd
, errno
);
1306 return LIBUSB_ERROR_IO
;
1310 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_GET_CAPABILITIES
, &hpriv
->caps
);
1312 if (errno
== ENOTTY
)
1313 usbi_dbg("%s: getcap not available", filename
);
1315 usbi_err(HANDLE_CTX(handle
),
1316 "%s: getcap failed (%d)", filename
, errno
);
1318 if (supports_flag_zero_packet
)
1319 hpriv
->caps
|= USBFS_CAP_ZERO_PACKET
;
1320 if (supports_flag_bulk_continuation
)
1321 hpriv
->caps
|= USBFS_CAP_BULK_CONTINUATION
;
1324 return usbi_add_pollfd(HANDLE_CTX(handle
), hpriv
->fd
, POLLOUT
);
1327 static void op_close(struct libusb_device_handle
*dev_handle
)
1329 int fd
= _device_handle_priv(dev_handle
)->fd
;
1330 usbi_remove_pollfd(HANDLE_CTX(dev_handle
), fd
);
1334 static int op_get_configuration(struct libusb_device_handle
*handle
,
1338 if (sysfs_can_relate_devices
!= 1)
1339 return LIBUSB_ERROR_NOT_SUPPORTED
;
1341 r
= sysfs_get_active_config(handle
->dev
, config
);
1345 if (*config
== -1) {
1346 usbi_err(HANDLE_CTX(handle
), "device unconfigured");
1353 static int op_set_configuration(struct libusb_device_handle
*handle
, int config
)
1355 struct linux_device_priv
*priv
= _device_priv(handle
->dev
);
1356 int fd
= _device_handle_priv(handle
)->fd
;
1357 int r
= ioctl(fd
, IOCTL_USBFS_SETCONFIG
, &config
);
1359 if (errno
== EINVAL
)
1360 return LIBUSB_ERROR_NOT_FOUND
;
1361 else if (errno
== EBUSY
)
1362 return LIBUSB_ERROR_BUSY
;
1363 else if (errno
== ENODEV
)
1364 return LIBUSB_ERROR_NO_DEVICE
;
1366 usbi_err(HANDLE_CTX(handle
), "failed, error %d errno %d", r
, errno
);
1367 return LIBUSB_ERROR_OTHER
;
1370 if (!sysfs_has_descriptors
) {
1371 /* update our cached active config descriptor */
1373 if (priv
->config_descriptor
) {
1374 free(priv
->config_descriptor
);
1375 priv
->config_descriptor
= NULL
;
1378 r
= cache_active_config(handle
->dev
, fd
, config
);
1380 usbi_warn(HANDLE_CTX(handle
),
1381 "failed to update cached config descriptor, error %d", r
);
1388 static int op_claim_interface(struct libusb_device_handle
*handle
, int iface
)
1390 int fd
= _device_handle_priv(handle
)->fd
;
1391 int r
= ioctl(fd
, IOCTL_USBFS_CLAIMINTF
, &iface
);
1393 if (errno
== ENOENT
)
1394 return LIBUSB_ERROR_NOT_FOUND
;
1395 else if (errno
== EBUSY
)
1396 return LIBUSB_ERROR_BUSY
;
1397 else if (errno
== ENODEV
)
1398 return LIBUSB_ERROR_NO_DEVICE
;
1400 usbi_err(HANDLE_CTX(handle
),
1401 "claim interface failed, error %d errno %d", r
, errno
);
1402 return LIBUSB_ERROR_OTHER
;
1407 static int op_release_interface(struct libusb_device_handle
*handle
, int iface
)
1409 int fd
= _device_handle_priv(handle
)->fd
;
1410 int r
= ioctl(fd
, IOCTL_USBFS_RELEASEINTF
, &iface
);
1412 if (errno
== ENODEV
)
1413 return LIBUSB_ERROR_NO_DEVICE
;
1415 usbi_err(HANDLE_CTX(handle
),
1416 "release interface failed, error %d errno %d", r
, errno
);
1417 return LIBUSB_ERROR_OTHER
;
1422 static int op_set_interface(struct libusb_device_handle
*handle
, int iface
,
1425 int fd
= _device_handle_priv(handle
)->fd
;
1426 struct usbfs_setinterface setintf
;
1429 setintf
.interface
= iface
;
1430 setintf
.altsetting
= altsetting
;
1431 r
= ioctl(fd
, IOCTL_USBFS_SETINTF
, &setintf
);
1433 if (errno
== EINVAL
)
1434 return LIBUSB_ERROR_NOT_FOUND
;
1435 else if (errno
== ENODEV
)
1436 return LIBUSB_ERROR_NO_DEVICE
;
1438 usbi_err(HANDLE_CTX(handle
),
1439 "setintf failed error %d errno %d", r
, errno
);
1440 return LIBUSB_ERROR_OTHER
;
1446 static int op_clear_halt(struct libusb_device_handle
*handle
,
1447 unsigned char endpoint
)
1449 int fd
= _device_handle_priv(handle
)->fd
;
1450 unsigned int _endpoint
= endpoint
;
1451 int r
= ioctl(fd
, IOCTL_USBFS_CLEAR_HALT
, &_endpoint
);
1453 if (errno
== ENOENT
)
1454 return LIBUSB_ERROR_NOT_FOUND
;
1455 else if (errno
== ENODEV
)
1456 return LIBUSB_ERROR_NO_DEVICE
;
1458 usbi_err(HANDLE_CTX(handle
),
1459 "clear_halt failed error %d errno %d", r
, errno
);
1460 return LIBUSB_ERROR_OTHER
;
1466 static int op_reset_device(struct libusb_device_handle
*handle
)
1468 int fd
= _device_handle_priv(handle
)->fd
;
1471 /* Doing a device reset will cause the usbfs driver to get unbound
1472 from any interfaces it is bound to. By voluntarily unbinding
1473 the usbfs driver ourself, we stop the kernel from rebinding
1474 the interface after reset (which would end up with the interface
1475 getting bound to the in kernel driver if any). */
1476 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1477 if (handle
->claimed_interfaces
& (1L << i
)) {
1478 op_release_interface(handle
, i
);
1482 usbi_mutex_lock(&handle
->lock
);
1483 r
= ioctl(fd
, IOCTL_USBFS_RESET
, NULL
);
1485 if (errno
== ENODEV
) {
1486 ret
= LIBUSB_ERROR_NOT_FOUND
;
1490 usbi_err(HANDLE_CTX(handle
),
1491 "reset failed error %d errno %d", r
, errno
);
1492 ret
= LIBUSB_ERROR_OTHER
;
1496 /* And re-claim any interfaces which were claimed before the reset */
1497 for (i
= 0; i
< USB_MAXINTERFACES
; i
++) {
1498 if (handle
->claimed_interfaces
& (1L << i
)) {
1499 r
= op_claim_interface(handle
, i
);
1501 usbi_warn(HANDLE_CTX(handle
),
1502 "failed to re-claim interface %d after reset", i
);
1503 handle
->claimed_interfaces
&= ~(1L << i
);
1508 usbi_mutex_unlock(&handle
->lock
);
1512 static int op_kernel_driver_active(struct libusb_device_handle
*handle
,
1515 int fd
= _device_handle_priv(handle
)->fd
;
1516 struct usbfs_getdriver getdrv
;
1519 getdrv
.interface
= interface
;
1520 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1522 if (errno
== ENODATA
)
1524 else if (errno
== ENODEV
)
1525 return LIBUSB_ERROR_NO_DEVICE
;
1527 usbi_err(HANDLE_CTX(handle
),
1528 "get driver failed error %d errno %d", r
, errno
);
1529 return LIBUSB_ERROR_OTHER
;
1535 static int op_detach_kernel_driver(struct libusb_device_handle
*handle
,
1538 int fd
= _device_handle_priv(handle
)->fd
;
1539 struct usbfs_ioctl command
;
1540 struct usbfs_getdriver getdrv
;
1543 command
.ifno
= interface
;
1544 command
.ioctl_code
= IOCTL_USBFS_DISCONNECT
;
1545 command
.data
= NULL
;
1547 getdrv
.interface
= interface
;
1548 r
= ioctl(fd
, IOCTL_USBFS_GETDRIVER
, &getdrv
);
1549 if (r
== 0 && strcmp(getdrv
.driver
, "usbfs") == 0)
1550 return LIBUSB_ERROR_NOT_FOUND
;
1552 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1554 if (errno
== ENODATA
)
1555 return LIBUSB_ERROR_NOT_FOUND
;
1556 else if (errno
== EINVAL
)
1557 return LIBUSB_ERROR_INVALID_PARAM
;
1558 else if (errno
== ENODEV
)
1559 return LIBUSB_ERROR_NO_DEVICE
;
1561 usbi_err(HANDLE_CTX(handle
),
1562 "detach failed error %d errno %d", r
, errno
);
1563 return LIBUSB_ERROR_OTHER
;
1569 static int op_attach_kernel_driver(struct libusb_device_handle
*handle
,
1572 int fd
= _device_handle_priv(handle
)->fd
;
1573 struct usbfs_ioctl command
;
1576 command
.ifno
= interface
;
1577 command
.ioctl_code
= IOCTL_USBFS_CONNECT
;
1578 command
.data
= NULL
;
1580 r
= ioctl(fd
, IOCTL_USBFS_IOCTL
, &command
);
1582 if (errno
== ENODATA
)
1583 return LIBUSB_ERROR_NOT_FOUND
;
1584 else if (errno
== EINVAL
)
1585 return LIBUSB_ERROR_INVALID_PARAM
;
1586 else if (errno
== ENODEV
)
1587 return LIBUSB_ERROR_NO_DEVICE
;
1588 else if (errno
== EBUSY
)
1589 return LIBUSB_ERROR_BUSY
;
1591 usbi_err(HANDLE_CTX(handle
),
1592 "attach failed error %d errno %d", r
, errno
);
1593 return LIBUSB_ERROR_OTHER
;
1594 } else if (r
== 0) {
1595 return LIBUSB_ERROR_NOT_FOUND
;
1601 static void op_destroy_device(struct libusb_device
*dev
)
1603 struct linux_device_priv
*priv
= _device_priv(dev
);
1604 if (!sysfs_has_descriptors
) {
1605 if (priv
->dev_descriptor
)
1606 free(priv
->dev_descriptor
);
1607 if (priv
->config_descriptor
)
1608 free(priv
->config_descriptor
);
1610 if (priv
->sysfs_dir
)
1611 free(priv
->sysfs_dir
);
1614 /* URBs are discarded in reverse order of submission to avoid races. */
1615 static int discard_urbs(struct usbi_transfer
*itransfer
, int first
, int last_plus_one
)
1617 struct libusb_transfer
*transfer
=
1618 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1619 struct linux_transfer_priv
*tpriv
=
1620 usbi_transfer_get_os_priv(itransfer
);
1621 struct linux_device_handle_priv
*dpriv
=
1622 _device_handle_priv(transfer
->dev_handle
);
1624 struct usbfs_urb
*urb
;
1626 for (i
= last_plus_one
- 1; i
>= first
; i
--) {
1627 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
== transfer
->type
)
1628 urb
= tpriv
->iso_urbs
[i
];
1630 urb
= &tpriv
->urbs
[i
];
1632 if (0 == ioctl(dpriv
->fd
, IOCTL_USBFS_DISCARDURB
, urb
))
1635 if (EINVAL
== errno
) {
1636 usbi_dbg("URB not found --> assuming ready to be reaped");
1637 if (i
== (last_plus_one
- 1))
1638 ret
= LIBUSB_ERROR_NOT_FOUND
;
1639 } else if (ENODEV
== errno
) {
1640 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1641 ret
= LIBUSB_ERROR_NO_DEVICE
;
1643 usbi_warn(TRANSFER_CTX(transfer
),
1644 "unrecognised discard errno %d", errno
);
1645 ret
= LIBUSB_ERROR_OTHER
;
1651 static void free_iso_urbs(struct linux_transfer_priv
*tpriv
)
1654 for (i
= 0; i
< tpriv
->num_urbs
; i
++) {
1655 struct usbfs_urb
*urb
= tpriv
->iso_urbs
[i
];
1661 free(tpriv
->iso_urbs
);
1662 tpriv
->iso_urbs
= NULL
;
1665 static int submit_bulk_transfer(struct usbi_transfer
*itransfer
,
1666 unsigned char urb_type
)
1668 struct libusb_transfer
*transfer
=
1669 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1670 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1671 struct linux_device_handle_priv
*dpriv
=
1672 _device_handle_priv(transfer
->dev_handle
);
1673 struct usbfs_urb
*urbs
;
1674 int is_out
= (transfer
->endpoint
& LIBUSB_ENDPOINT_DIR_MASK
)
1675 == LIBUSB_ENDPOINT_OUT
;
1676 int bulk_buffer_len
, use_bulk_continuation
;
1682 return LIBUSB_ERROR_BUSY
;
1684 if (is_out
&& (transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
) &&
1685 !(dpriv
->caps
& USBFS_CAP_ZERO_PACKET
))
1686 return LIBUSB_ERROR_NOT_SUPPORTED
;
1689 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1690 * around this by splitting large transfers into 16k blocks, and then
1691 * submit all urbs at once. it would be simpler to submit one urb at
1692 * a time, but there is a big performance gain doing it this way.
1694 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1695 * using arbritary large transfers can still be a bad idea though, as
1696 * the kernel needs to allocate physical contiguous memory for this,
1697 * which may fail for large buffers.
1699 * The kernel solves this problem by splitting the transfer into
1700 * blocks itself when the host-controller is scatter-gather capable
1701 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1703 * Last, there is the issue of short-transfers when splitting, for
1704 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1705 * is needed, but this is not always available.
1707 if (dpriv
->caps
& USBFS_CAP_BULK_SCATTER_GATHER
) {
1708 /* Good! Just submit everything in one go */
1709 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1710 use_bulk_continuation
= 0;
1711 } else if (dpriv
->caps
& USBFS_CAP_BULK_CONTINUATION
) {
1712 /* Split the transfers and use bulk-continuation to
1713 avoid issues with short-transfers */
1714 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1715 use_bulk_continuation
= 1;
1716 } else if (dpriv
->caps
& USBFS_CAP_NO_PACKET_SIZE_LIM
) {
1717 /* Don't split, assume the kernel can alloc the buffer
1718 (otherwise the submit will fail with -ENOMEM) */
1719 bulk_buffer_len
= transfer
->length
? transfer
->length
: 1;
1720 use_bulk_continuation
= 0;
1722 /* Bad, splitting without bulk-continuation, short transfers
1723 which end before the last urb will not work reliable! */
1724 /* Note we don't warn here as this is "normal" on kernels <
1725 2.6.32 and not a problem for most applications */
1726 bulk_buffer_len
= MAX_BULK_BUFFER_LENGTH
;
1727 use_bulk_continuation
= 0;
1730 int num_urbs
= transfer
->length
/ bulk_buffer_len
;
1731 int last_urb_partial
= 0;
1733 if (transfer
->length
== 0) {
1735 } else if ((transfer
->length
% bulk_buffer_len
) > 0) {
1736 last_urb_partial
= 1;
1739 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs
,
1741 alloc_size
= num_urbs
* sizeof(struct usbfs_urb
);
1742 urbs
= calloc(1, alloc_size
);
1744 return LIBUSB_ERROR_NO_MEM
;
1746 tpriv
->num_urbs
= num_urbs
;
1747 tpriv
->num_retired
= 0;
1748 tpriv
->reap_action
= NORMAL
;
1749 tpriv
->reap_status
= LIBUSB_TRANSFER_COMPLETED
;
1751 for (i
= 0; i
< num_urbs
; i
++) {
1752 struct usbfs_urb
*urb
= &urbs
[i
];
1753 urb
->usercontext
= itransfer
;
1754 urb
->type
= urb_type
;
1755 urb
->endpoint
= transfer
->endpoint
;
1756 urb
->buffer
= transfer
->buffer
+ (i
* bulk_buffer_len
);
1757 if (use_bulk_continuation
&& !is_out
&& (i
!= num_urbs
- 1))
1758 urb
->flags
= USBFS_URB_SHORT_NOT_OK
;
1759 if (i
== num_urbs
- 1 && last_urb_partial
)
1760 urb
->buffer_length
= transfer
->length
% bulk_buffer_len
;
1761 else if (transfer
->length
== 0)
1762 urb
->buffer_length
= 0;
1764 urb
->buffer_length
= bulk_buffer_len
;
1766 if (i
> 0 && use_bulk_continuation
)
1767 urb
->flags
|= USBFS_URB_BULK_CONTINUATION
;
1769 /* we have already checked that the flag is supported */
1770 if (is_out
&& i
== num_urbs
- 1 &&
1771 transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
)
1772 urb
->flags
|= USBFS_URB_ZERO_PACKET
;
1774 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
1776 if (errno
== ENODEV
) {
1777 r
= LIBUSB_ERROR_NO_DEVICE
;
1779 usbi_err(TRANSFER_CTX(transfer
),
1780 "submiturb failed error %d errno=%d", r
, errno
);
1781 r
= LIBUSB_ERROR_IO
;
1784 /* if the first URB submission fails, we can simply free up and
1785 * return failure immediately. */
1787 usbi_dbg("first URB failed, easy peasy");
1793 /* if it's not the first URB that failed, the situation is a bit
1794 * tricky. we may need to discard all previous URBs. there are
1796 * - discarding is asynchronous - discarded urbs will be reaped
1797 * later. the user must not have freed the transfer when the
1798 * discarded URBs are reaped, otherwise libusbx will be using
1800 * - the earlier URBs may have completed successfully and we do
1801 * not want to throw away any data.
1802 * - this URB failing may be no error; EREMOTEIO means that
1803 * this transfer simply didn't need all the URBs we submitted
1804 * so, we report that the transfer was submitted successfully and
1805 * in case of error we discard all previous URBs. later when
1806 * the final reap completes we can report error to the user,
1807 * or success if an earlier URB was completed successfully.
1809 tpriv
->reap_action
= EREMOTEIO
== errno
? COMPLETED_EARLY
: SUBMIT_FAILED
;
1811 /* The URBs we haven't submitted yet we count as already
1813 tpriv
->num_retired
+= num_urbs
- i
;
1815 /* If we completed short then don't try to discard. */
1816 if (COMPLETED_EARLY
== tpriv
->reap_action
)
1819 discard_urbs(itransfer
, 0, i
);
1821 usbi_dbg("reporting successful submission but waiting for %d "
1822 "discards before reporting error", i
);
1830 static int submit_iso_transfer(struct usbi_transfer
*itransfer
)
1832 struct libusb_transfer
*transfer
=
1833 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1834 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1835 struct linux_device_handle_priv
*dpriv
=
1836 _device_handle_priv(transfer
->dev_handle
);
1837 struct usbfs_urb
**urbs
;
1839 int num_packets
= transfer
->num_iso_packets
;
1841 int this_urb_len
= 0;
1843 int packet_offset
= 0;
1844 unsigned int packet_len
;
1845 unsigned char *urb_buffer
= transfer
->buffer
;
1847 if (tpriv
->iso_urbs
)
1848 return LIBUSB_ERROR_BUSY
;
1850 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1851 * into smaller units to meet such restriction, then fire off all the
1852 * units at once. it would be simpler if we just fired one unit at a time,
1853 * but there is a big performance gain through doing it this way.
1855 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1856 * using arbritary large transfers is still be a bad idea though, as
1857 * the kernel needs to allocate physical contiguous memory for this,
1858 * which may fail for large buffers.
1861 /* calculate how many URBs we need */
1862 for (i
= 0; i
< num_packets
; i
++) {
1863 unsigned int space_remaining
= MAX_ISO_BUFFER_LENGTH
- this_urb_len
;
1864 packet_len
= transfer
->iso_packet_desc
[i
].length
;
1866 if (packet_len
> space_remaining
) {
1868 this_urb_len
= packet_len
;
1870 this_urb_len
+= packet_len
;
1873 usbi_dbg("need %d 32k URBs for transfer", num_urbs
);
1875 alloc_size
= num_urbs
* sizeof(*urbs
);
1876 urbs
= calloc(1, alloc_size
);
1878 return LIBUSB_ERROR_NO_MEM
;
1880 tpriv
->iso_urbs
= urbs
;
1881 tpriv
->num_urbs
= num_urbs
;
1882 tpriv
->num_retired
= 0;
1883 tpriv
->reap_action
= NORMAL
;
1884 tpriv
->iso_packet_offset
= 0;
1886 /* allocate + initialize each URB with the correct number of packets */
1887 for (i
= 0; i
< num_urbs
; i
++) {
1888 struct usbfs_urb
*urb
;
1889 unsigned int space_remaining_in_urb
= MAX_ISO_BUFFER_LENGTH
;
1890 int urb_packet_offset
= 0;
1891 unsigned char *urb_buffer_orig
= urb_buffer
;
1895 /* swallow up all the packets we can fit into this URB */
1896 while (packet_offset
< transfer
->num_iso_packets
) {
1897 packet_len
= transfer
->iso_packet_desc
[packet_offset
].length
;
1898 if (packet_len
<= space_remaining_in_urb
) {
1900 urb_packet_offset
++;
1902 space_remaining_in_urb
-= packet_len
;
1903 urb_buffer
+= packet_len
;
1905 /* it can't fit, save it for the next URB */
1910 alloc_size
= sizeof(*urb
)
1911 + (urb_packet_offset
* sizeof(struct usbfs_iso_packet_desc
));
1912 urb
= calloc(1, alloc_size
);
1914 free_iso_urbs(tpriv
);
1915 return LIBUSB_ERROR_NO_MEM
;
1919 /* populate packet lengths */
1920 for (j
= 0, k
= packet_offset
- urb_packet_offset
;
1921 k
< packet_offset
; k
++, j
++) {
1922 packet_len
= transfer
->iso_packet_desc
[k
].length
;
1923 urb
->iso_frame_desc
[j
].length
= packet_len
;
1926 urb
->usercontext
= itransfer
;
1927 urb
->type
= USBFS_URB_TYPE_ISO
;
1928 /* FIXME: interface for non-ASAP data? */
1929 urb
->flags
= USBFS_URB_ISO_ASAP
;
1930 urb
->endpoint
= transfer
->endpoint
;
1931 urb
->number_of_packets
= urb_packet_offset
;
1932 urb
->buffer
= urb_buffer_orig
;
1936 for (i
= 0; i
< num_urbs
; i
++) {
1937 int r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urbs
[i
]);
1939 if (errno
== ENODEV
) {
1940 r
= LIBUSB_ERROR_NO_DEVICE
;
1942 usbi_err(TRANSFER_CTX(transfer
),
1943 "submiturb failed error %d errno=%d", r
, errno
);
1944 r
= LIBUSB_ERROR_IO
;
1947 /* if the first URB submission fails, we can simply free up and
1948 * return failure immediately. */
1950 usbi_dbg("first URB failed, easy peasy");
1951 free_iso_urbs(tpriv
);
1955 /* if it's not the first URB that failed, the situation is a bit
1956 * tricky. we must discard all previous URBs. there are
1958 * - discarding is asynchronous - discarded urbs will be reaped
1959 * later. the user must not have freed the transfer when the
1960 * discarded URBs are reaped, otherwise libusbx will be using
1962 * - the earlier URBs may have completed successfully and we do
1963 * not want to throw away any data.
1964 * so, in this case we discard all the previous URBs BUT we report
1965 * that the transfer was submitted successfully. then later when
1966 * the final discard completes we can report error to the user.
1968 tpriv
->reap_action
= SUBMIT_FAILED
;
1970 /* The URBs we haven't submitted yet we count as already
1972 tpriv
->num_retired
= num_urbs
- i
;
1973 discard_urbs(itransfer
, 0, i
);
1975 usbi_dbg("reporting successful submission but waiting for %d "
1976 "discards before reporting error", i
);
1984 static int submit_control_transfer(struct usbi_transfer
*itransfer
)
1986 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1987 struct libusb_transfer
*transfer
=
1988 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1989 struct linux_device_handle_priv
*dpriv
=
1990 _device_handle_priv(transfer
->dev_handle
);
1991 struct usbfs_urb
*urb
;
1995 return LIBUSB_ERROR_BUSY
;
1997 if (transfer
->length
- LIBUSB_CONTROL_SETUP_SIZE
> MAX_CTRL_BUFFER_LENGTH
)
1998 return LIBUSB_ERROR_INVALID_PARAM
;
2000 urb
= calloc(1, sizeof(struct usbfs_urb
));
2002 return LIBUSB_ERROR_NO_MEM
;
2004 tpriv
->num_urbs
= 1;
2005 tpriv
->reap_action
= NORMAL
;
2007 urb
->usercontext
= itransfer
;
2008 urb
->type
= USBFS_URB_TYPE_CONTROL
;
2009 urb
->endpoint
= transfer
->endpoint
;
2010 urb
->buffer
= transfer
->buffer
;
2011 urb
->buffer_length
= transfer
->length
;
2013 r
= ioctl(dpriv
->fd
, IOCTL_USBFS_SUBMITURB
, urb
);
2017 if (errno
== ENODEV
)
2018 return LIBUSB_ERROR_NO_DEVICE
;
2020 usbi_err(TRANSFER_CTX(transfer
),
2021 "submiturb failed error %d errno=%d", r
, errno
);
2022 return LIBUSB_ERROR_IO
;
2027 static int op_submit_transfer(struct usbi_transfer
*itransfer
)
2029 struct libusb_transfer
*transfer
=
2030 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2032 switch (transfer
->type
) {
2033 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2034 return submit_control_transfer(itransfer
);
2035 case LIBUSB_TRANSFER_TYPE_BULK
:
2036 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_BULK
);
2037 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2038 return submit_bulk_transfer(itransfer
, USBFS_URB_TYPE_INTERRUPT
);
2039 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2040 return submit_iso_transfer(itransfer
);
2042 usbi_err(TRANSFER_CTX(transfer
),
2043 "unknown endpoint type %d", transfer
->type
);
2044 return LIBUSB_ERROR_INVALID_PARAM
;
2048 static int op_cancel_transfer(struct usbi_transfer
*itransfer
)
2050 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2051 struct libusb_transfer
*transfer
=
2052 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2054 switch (transfer
->type
) {
2055 case LIBUSB_TRANSFER_TYPE_BULK
:
2056 if (tpriv
->reap_action
== ERROR
)
2058 /* else, fall through */
2059 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2060 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2061 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2062 tpriv
->reap_action
= CANCELLED
;
2065 usbi_err(TRANSFER_CTX(transfer
),
2066 "unknown endpoint type %d", transfer
->type
);
2067 return LIBUSB_ERROR_INVALID_PARAM
;
2071 return LIBUSB_ERROR_NOT_FOUND
;
2073 return discard_urbs(itransfer
, 0, tpriv
->num_urbs
);
2076 static void op_clear_transfer_priv(struct usbi_transfer
*itransfer
)
2078 struct libusb_transfer
*transfer
=
2079 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2080 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2082 /* urbs can be freed also in submit_transfer so lock mutex first */
2083 switch (transfer
->type
) {
2084 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2085 case LIBUSB_TRANSFER_TYPE_BULK
:
2086 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2087 usbi_mutex_lock(&itransfer
->lock
);
2091 usbi_mutex_unlock(&itransfer
->lock
);
2093 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2094 usbi_mutex_lock(&itransfer
->lock
);
2095 if (tpriv
->iso_urbs
)
2096 free_iso_urbs(tpriv
);
2097 usbi_mutex_unlock(&itransfer
->lock
);
2100 usbi_err(TRANSFER_CTX(transfer
),
2101 "unknown endpoint type %d", transfer
->type
);
2105 static int handle_bulk_completion(struct usbi_transfer
*itransfer
,
2106 struct usbfs_urb
*urb
)
2108 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2109 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2110 int urb_idx
= urb
- tpriv
->urbs
;
2112 usbi_mutex_lock(&itransfer
->lock
);
2113 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb
->status
,
2114 urb_idx
+ 1, tpriv
->num_urbs
);
2116 tpriv
->num_retired
++;
2118 if (tpriv
->reap_action
!= NORMAL
) {
2119 /* cancelled, submit_fail, or completed early */
2120 usbi_dbg("abnormal reap: urb status %d", urb
->status
);
2122 /* even though we're in the process of cancelling, it's possible that
2123 * we may receive some data in these URBs that we don't want to lose.
2125 * 1. while the kernel is cancelling all the packets that make up an
2126 * URB, a few of them might complete. so we get back a successful
2127 * cancellation *and* some data.
2128 * 2. we receive a short URB which marks the early completion condition,
2129 * so we start cancelling the remaining URBs. however, we're too
2130 * slow and another URB completes (or at least completes partially).
2131 * (this can't happen since we always use BULK_CONTINUATION.)
2133 * When this happens, our objectives are not to lose any "surplus" data,
2134 * and also to stick it at the end of the previously-received data
2135 * (closing any holes), so that libusbx reports the total amount of
2136 * transferred data and presents it in a contiguous chunk.
2138 if (urb
->actual_length
> 0) {
2139 unsigned char *target
= transfer
->buffer
+ itransfer
->transferred
;
2140 usbi_dbg("received %d bytes of surplus data", urb
->actual_length
);
2141 if (urb
->buffer
!= target
) {
2142 usbi_dbg("moving surplus data from offset %d to offset %d",
2143 (unsigned char *) urb
->buffer
- transfer
->buffer
,
2144 target
- transfer
->buffer
);
2145 memmove(target
, urb
->buffer
, urb
->actual_length
);
2147 itransfer
->transferred
+= urb
->actual_length
;
2150 if (tpriv
->num_retired
== tpriv
->num_urbs
) {
2151 usbi_dbg("abnormal reap: last URB handled, reporting");
2152 if (tpriv
->reap_action
!= COMPLETED_EARLY
&&
2153 tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2154 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2160 itransfer
->transferred
+= urb
->actual_length
;
2162 /* Many of these errors can occur on *any* urb of a multi-urb
2163 * transfer. When they do, we tear down the rest of the transfer.
2165 switch (urb
->status
) {
2168 case -EREMOTEIO
: /* short transfer */
2170 case -ENOENT
: /* cancelled */
2175 usbi_dbg("device removed");
2176 tpriv
->reap_status
= LIBUSB_TRANSFER_NO_DEVICE
;
2177 goto cancel_remaining
;
2179 usbi_dbg("detected endpoint stall");
2180 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2181 tpriv
->reap_status
= LIBUSB_TRANSFER_STALL
;
2182 goto cancel_remaining
;
2184 /* overflow can only ever occur in the last urb */
2185 usbi_dbg("overflow, actual_length=%d", urb
->actual_length
);
2186 if (tpriv
->reap_status
== LIBUSB_TRANSFER_COMPLETED
)
2187 tpriv
->reap_status
= LIBUSB_TRANSFER_OVERFLOW
;
2194 usbi_dbg("low level error %d", urb
->status
);
2195 tpriv
->reap_action
= ERROR
;
2196 goto cancel_remaining
;
2198 usbi_warn(ITRANSFER_CTX(itransfer
),
2199 "unrecognised urb status %d", urb
->status
);
2200 tpriv
->reap_action
= ERROR
;
2201 goto cancel_remaining
;
2204 /* if we're the last urb or we got less data than requested then we're
2206 if (urb_idx
== tpriv
->num_urbs
- 1) {
2207 usbi_dbg("last URB in transfer --> complete!");
2209 } else if (urb
->actual_length
< urb
->buffer_length
) {
2210 usbi_dbg("short transfer %d/%d --> complete!",
2211 urb
->actual_length
, urb
->buffer_length
);
2212 if (tpriv
->reap_action
== NORMAL
)
2213 tpriv
->reap_action
= COMPLETED_EARLY
;
2218 if (ERROR
== tpriv
->reap_action
&& LIBUSB_TRANSFER_COMPLETED
== tpriv
->reap_status
)
2219 tpriv
->reap_status
= LIBUSB_TRANSFER_ERROR
;
2221 if (tpriv
->num_retired
== tpriv
->num_urbs
) /* nothing to cancel */
2224 /* cancel remaining urbs and wait for their completion before
2225 * reporting results */
2226 discard_urbs(itransfer
, urb_idx
+ 1, tpriv
->num_urbs
);
2229 usbi_mutex_unlock(&itransfer
->lock
);
2235 usbi_mutex_unlock(&itransfer
->lock
);
2236 return CANCELLED
== tpriv
->reap_action
?
2237 usbi_handle_transfer_cancellation(itransfer
) :
2238 usbi_handle_transfer_completion(itransfer
, tpriv
->reap_status
);
2241 static int handle_iso_completion(struct usbi_transfer
*itransfer
,
2242 struct usbfs_urb
*urb
)
2244 struct libusb_transfer
*transfer
=
2245 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2246 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2247 int num_urbs
= tpriv
->num_urbs
;
2250 enum libusb_transfer_status status
= LIBUSB_TRANSFER_COMPLETED
;
2252 usbi_mutex_lock(&itransfer
->lock
);
2253 for (i
= 0; i
< num_urbs
; i
++) {
2254 if (urb
== tpriv
->iso_urbs
[i
]) {
2260 usbi_err(TRANSFER_CTX(transfer
), "could not locate urb!");
2261 usbi_mutex_unlock(&itransfer
->lock
);
2262 return LIBUSB_ERROR_NOT_FOUND
;
2265 usbi_dbg("handling completion status %d of iso urb %d/%d", urb
->status
,
2268 /* copy isochronous results back in */
2270 for (i
= 0; i
< urb
->number_of_packets
; i
++) {
2271 struct usbfs_iso_packet_desc
*urb_desc
= &urb
->iso_frame_desc
[i
];
2272 struct libusb_iso_packet_descriptor
*lib_desc
=
2273 &transfer
->iso_packet_desc
[tpriv
->iso_packet_offset
++];
2274 lib_desc
->status
= LIBUSB_TRANSFER_COMPLETED
;
2275 switch (urb_desc
->status
) {
2278 case -ENOENT
: /* cancelled */
2283 usbi_dbg("device removed");
2284 lib_desc
->status
= LIBUSB_TRANSFER_NO_DEVICE
;
2287 usbi_dbg("detected endpoint stall");
2288 lib_desc
->status
= LIBUSB_TRANSFER_STALL
;
2291 usbi_dbg("overflow error");
2292 lib_desc
->status
= LIBUSB_TRANSFER_OVERFLOW
;
2300 usbi_dbg("low-level USB error %d", urb_desc
->status
);
2301 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2304 usbi_warn(TRANSFER_CTX(transfer
),
2305 "unrecognised urb status %d", urb_desc
->status
);
2306 lib_desc
->status
= LIBUSB_TRANSFER_ERROR
;
2309 lib_desc
->actual_length
= urb_desc
->actual_length
;
2312 tpriv
->num_retired
++;
2314 if (tpriv
->reap_action
!= NORMAL
) { /* cancelled or submit_fail */
2315 usbi_dbg("CANCEL: urb status %d", urb
->status
);
2317 if (tpriv
->num_retired
== num_urbs
) {
2318 usbi_dbg("CANCEL: last URB handled, reporting");
2319 free_iso_urbs(tpriv
);
2320 if (tpriv
->reap_action
== CANCELLED
) {
2321 usbi_mutex_unlock(&itransfer
->lock
);
2322 return usbi_handle_transfer_cancellation(itransfer
);
2324 usbi_mutex_unlock(&itransfer
->lock
);
2325 return usbi_handle_transfer_completion(itransfer
,
2326 LIBUSB_TRANSFER_ERROR
);
2332 switch (urb
->status
) {
2335 case -ENOENT
: /* cancelled */
2339 usbi_dbg("device removed");
2340 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2343 usbi_warn(TRANSFER_CTX(transfer
),
2344 "unrecognised urb status %d", urb
->status
);
2345 status
= LIBUSB_TRANSFER_ERROR
;
2349 /* if we're the last urb then we're done */
2350 if (urb_idx
== num_urbs
) {
2351 usbi_dbg("last URB in transfer --> complete!");
2352 free_iso_urbs(tpriv
);
2353 usbi_mutex_unlock(&itransfer
->lock
);
2354 return usbi_handle_transfer_completion(itransfer
, status
);
2358 usbi_mutex_unlock(&itransfer
->lock
);
2362 static int handle_control_completion(struct usbi_transfer
*itransfer
,
2363 struct usbfs_urb
*urb
)
2365 struct linux_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
2368 usbi_mutex_lock(&itransfer
->lock
);
2369 usbi_dbg("handling completion status %d", urb
->status
);
2371 itransfer
->transferred
+= urb
->actual_length
;
2373 if (tpriv
->reap_action
== CANCELLED
) {
2374 if (urb
->status
!= 0 && urb
->status
!= -ENOENT
)
2375 usbi_warn(ITRANSFER_CTX(itransfer
),
2376 "cancel: unrecognised urb status %d", urb
->status
);
2379 usbi_mutex_unlock(&itransfer
->lock
);
2380 return usbi_handle_transfer_cancellation(itransfer
);
2383 switch (urb
->status
) {
2385 status
= LIBUSB_TRANSFER_COMPLETED
;
2387 case -ENOENT
: /* cancelled */
2388 status
= LIBUSB_TRANSFER_CANCELLED
;
2392 usbi_dbg("device removed");
2393 status
= LIBUSB_TRANSFER_NO_DEVICE
;
2396 usbi_dbg("unsupported control request");
2397 status
= LIBUSB_TRANSFER_STALL
;
2400 usbi_dbg("control overflow error");
2401 status
= LIBUSB_TRANSFER_OVERFLOW
;
2408 usbi_dbg("low-level bus error occurred");
2409 status
= LIBUSB_TRANSFER_ERROR
;
2412 usbi_warn(ITRANSFER_CTX(itransfer
),
2413 "unrecognised urb status %d", urb
->status
);
2414 status
= LIBUSB_TRANSFER_ERROR
;
2420 usbi_mutex_unlock(&itransfer
->lock
);
2421 return usbi_handle_transfer_completion(itransfer
, status
);
2424 static int reap_for_handle(struct libusb_device_handle
*handle
)
2426 struct linux_device_handle_priv
*hpriv
= _device_handle_priv(handle
);
2428 struct usbfs_urb
*urb
;
2429 struct usbi_transfer
*itransfer
;
2430 struct libusb_transfer
*transfer
;
2432 r
= ioctl(hpriv
->fd
, IOCTL_USBFS_REAPURBNDELAY
, &urb
);
2433 if (r
== -1 && errno
== EAGAIN
)
2436 if (errno
== ENODEV
)
2437 return LIBUSB_ERROR_NO_DEVICE
;
2439 usbi_err(HANDLE_CTX(handle
), "reap failed error %d errno=%d",
2441 return LIBUSB_ERROR_IO
;
2444 itransfer
= urb
->usercontext
;
2445 transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
2447 usbi_dbg("urb type=%d status=%d transferred=%d", urb
->type
, urb
->status
,
2448 urb
->actual_length
);
2450 switch (transfer
->type
) {
2451 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
2452 return handle_iso_completion(itransfer
, urb
);
2453 case LIBUSB_TRANSFER_TYPE_BULK
:
2454 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
2455 return handle_bulk_completion(itransfer
, urb
);
2456 case LIBUSB_TRANSFER_TYPE_CONTROL
:
2457 return handle_control_completion(itransfer
, urb
);
2459 usbi_err(HANDLE_CTX(handle
), "unrecognised endpoint type %x",
2461 return LIBUSB_ERROR_OTHER
;
2465 static int op_handle_events(struct libusb_context
*ctx
,
2466 struct pollfd
*fds
, POLL_NFDS_TYPE nfds
, int num_ready
)
2471 usbi_mutex_lock(&ctx
->open_devs_lock
);
2472 for (i
= 0; i
< nfds
&& num_ready
> 0; i
++) {
2473 struct pollfd
*pollfd
= &fds
[i
];
2474 struct libusb_device_handle
*handle
;
2475 struct linux_device_handle_priv
*hpriv
= NULL
;
2477 if (!pollfd
->revents
)
2481 list_for_each_entry(handle
, &ctx
->open_devs
, list
, struct libusb_device_handle
) {
2482 hpriv
= _device_handle_priv(handle
);
2483 if (hpriv
->fd
== pollfd
->fd
)
2487 if (pollfd
->revents
& POLLERR
) {
2488 usbi_remove_pollfd(HANDLE_CTX(handle
), hpriv
->fd
);
2489 usbi_handle_disconnect(handle
);
2494 r
= reap_for_handle(handle
);
2496 if (r
== 1 || r
== LIBUSB_ERROR_NO_DEVICE
)
2504 usbi_mutex_unlock(&ctx
->open_devs_lock
);
2508 static int op_clock_gettime(int clk_id
, struct timespec
*tp
)
2511 case USBI_CLOCK_MONOTONIC
:
2512 return clock_gettime(monotonic_clkid
, tp
);
2513 case USBI_CLOCK_REALTIME
:
2514 return clock_gettime(CLOCK_REALTIME
, tp
);
2516 return LIBUSB_ERROR_INVALID_PARAM
;
2520 #ifdef USBI_TIMERFD_AVAILABLE
2521 static clockid_t
op_get_timerfd_clockid(void)
2523 return monotonic_clkid
;
2528 const struct usbi_os_backend linux_usbfs_backend
= {
2529 .name
= "Linux usbfs",
2530 .caps
= USBI_CAP_HAS_HID_ACCESS
|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
,
2533 .get_device_list
= op_get_device_list
,
2534 .get_device_descriptor
= op_get_device_descriptor
,
2535 .get_active_config_descriptor
= op_get_active_config_descriptor
,
2536 .get_config_descriptor
= op_get_config_descriptor
,
2540 .get_configuration
= op_get_configuration
,
2541 .set_configuration
= op_set_configuration
,
2542 .claim_interface
= op_claim_interface
,
2543 .release_interface
= op_release_interface
,
2545 .set_interface_altsetting
= op_set_interface
,
2546 .clear_halt
= op_clear_halt
,
2547 .reset_device
= op_reset_device
,
2549 .kernel_driver_active
= op_kernel_driver_active
,
2550 .detach_kernel_driver
= op_detach_kernel_driver
,
2551 .attach_kernel_driver
= op_attach_kernel_driver
,
2553 .destroy_device
= op_destroy_device
,
2555 .submit_transfer
= op_submit_transfer
,
2556 .cancel_transfer
= op_cancel_transfer
,
2557 .clear_transfer_priv
= op_clear_transfer_priv
,
2559 .handle_events
= op_handle_events
,
2561 .clock_gettime
= op_clock_gettime
,
2563 #ifdef USBI_TIMERFD_AVAILABLE
2564 .get_timerfd_clockid
= op_get_timerfd_clockid
,
2567 .device_priv_size
= sizeof(struct linux_device_priv
),
2568 .device_handle_priv_size
= sizeof(struct linux_device_handle_priv
),
2569 .transfer_priv_size
= sizeof(struct linux_transfer_priv
),
2570 .add_iso_packet_size
= 0,