1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
2 /*********************************************************************
3 * modified some function to avoid crash, support Android
4 * Copyright (C) 2014-2016 saki@serenegiant All rights reserved.
5 *********************************************************************/
7 * Android usbfs backend for libusb
8 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
9 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
10 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
11 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #define LOG_TAG "libusb/usbfs"
31 #if 1 // デバッグ情報を出さない時1
33 #define LOG_NDEBUG // LOGV/LOGD/MARKを出力しない時
35 #undef USE_LOGALL // 指定したLOGxだけを出力
40 #define GET_RAW_DESCRIPTOR
53 #include <sys/ioctl.h>
55 #include <sys/types.h>
56 #include <sys/utsname.h>
61 #include "android_usbfs.h"
64 * opening a usbfs node causes the device to be resumed, so we attempt to
65 * avoid this during enumeration.
67 * sysfs allows us to read the kernel's in-memory copies of device descriptors
68 * and so forth, avoiding the need to open the device:
69 * - The binary "descriptors" file contains all config descriptors since
70 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
71 * - The binary "descriptors" file was added in 2.6.23, commit
72 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
73 * active config descriptors
74 * - The "busnum" file was added in 2.6.22, commit
75 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
76 * - The "devnum" file has been present since pre-2.6.18
77 * - the "bConfigurationValue" file has been present since pre-2.6.18
79 * If we have bConfigurationValue, busnum, and devnum, then we can determine
80 * the active configuration without having to open the usbfs node in RDWR mode.
81 * The busnum file is important as that is the only way we can relate sysfs
82 * devices to usbfs nodes.
84 * If we also have all descriptors, we can obtain the device descriptor and
85 * configuration without touching usbfs at all.
88 /* endianness for multi-byte fields:
90 * Descriptors exposed by usbfs have the multi-byte fields in the device
91 * descriptor as host endian. Multi-byte fields in the other descriptors are
92 * bus-endian. The kernel documentation says otherwise, but it is wrong.
94 * In sysfs all descriptors are bus-endian.
97 static const char *usbfs_path = NULL;
99 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
100 static int usbdev_names = 0;
102 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
103 * allows us to mark URBs as being part of a specific logical transfer when
104 * we submit them to the kernel. then, on any error except a cancellation, all
105 * URBs within that transfer will be cancelled and no more URBs will be
106 * accepted for the transfer, meaning that no more data can creep in.
108 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
109 * (in either direction) except the first.
110 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
111 * last; it means that the kernel should treat a short reply as an error.
112 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
113 * transfers can't be short unless there's already some sort of error), and
114 * setting this flag is disallowed (a kernel with USB debugging enabled will
117 static int supports_flag_bulk_continuation = -1;
119 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
120 * allows us to mark URBs that should be followed by a zero length data
121 * packet, which can be required by device- or class-specific protocols.
123 static int supports_flag_zero_packet = -1;
125 /* clock ID for monotonic clock, as not all clock sources are available on all
126 * systems. appropriate choice made at initialization time. */
127 static clockid_t monotonic_clkid = -1;
129 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
130 * to sysfs, so we can relate devices. This also implies that we can read
131 * the active configuration through bConfigurationValue */
132 static int sysfs_can_relate_devices = -1;
134 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
135 * config descriptors (rather then just the active config) to the sysfs
136 * descriptors file, so from then on we can use them. */
137 static int sysfs_has_descriptors = -1;
139 /* how many times have we initted (and not exited) ? */
140 static int init_count = 0;
142 /* Serialize hotplug start/stop */
143 usbi_mutex_static_t android_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
144 /* Serialize scan-devices, event-thread, and poll */
145 usbi_mutex_static_t android_hotplug_lock = USBI_MUTEX_INITIALIZER;
147 static int android_start_event_monitor(void);
148 static int android_stop_event_monitor(void);
149 static int android_scan_devices(struct libusb_context *ctx);
150 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
151 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
153 #if !defined(USE_UDEV)
154 static int android_default_scan_devices(struct libusb_context *ctx);
157 struct android_device_priv {
159 unsigned char *descriptors;
161 int active_config; /* cache val for !sysfs_can_relate_devices */
165 struct android_device_handle_priv {
172 /* submission failed after the first URB, so await cancellation/completion
173 * of all the others */
176 /* cancelled by user or timeout */
179 /* completed multi-URB transfer in non-final URB */
182 /* one or more urbs encountered a low-level error */
186 struct android_transfer_priv {
188 struct usbfs_urb *urbs;
189 struct usbfs_urb **iso_urbs;
192 enum reap_action reap_action;
195 enum libusb_transfer_status reap_status;
197 /* next iso packet in user-supplied transfer to be populated */
198 int iso_packet_offset;
202 static void dump_urb(int ix, int fd, struct usbfs_urb *urb) {
203 LOGI("%d:fd=%d", ix, fd);
204 int ret = fcntl(fd, F_GETFL);
205 if (UNLIKELY(ret == -1)) {
206 LOGE("Failed to get fd flags: %d", errno);
208 LOGI("ファイフディスクリプタフラグ:%x", ret);
209 LOGI("O_ACCMODE:%x", ret & O_ACCMODE); // 0:読み込み専用, 1:書き込み専用, 2;読み書き可
210 LOGI("ノンブロッキングかどうか:%d", ret & O_NONBLOCK); // 0:ブロッキング
211 LOGI("%d:type=%d,endpopint=0x%02x,status=%d,flag=%d", ix, urb->type, urb->endpoint, urb->status, urb->flags);
212 LOGI("%d:buffer=%p,buffer_length=%d,actual_length=%d,start_frame=%d", ix, urb->buffer, urb->buffer_length, urb->actual_length, urb->start_frame);
213 LOGI("%d:number_of_packets=%d,error_count=%d,signr=%d", ix, urb->number_of_packets, urb->error_count, urb->signr);
214 LOGI("%d:usercontext=%p,iso_frame_desc=%p", ix, urb->usercontext, urb->iso_frame_desc);
219 * this is original _get_usbfs_fd (name changed to __get_usbfs_fd)
221 static int __get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent) {
223 struct libusb_context *ctx = DEVICE_CTX(dev);
229 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
230 usbfs_path, dev->bus_number, dev->device_address);
232 snprintf(path, PATH_MAX, "%s/%03d/%03d",
233 usbfs_path, dev->bus_number, dev->device_address);
235 fd = open(path, mode);
236 if (LIKELY(fd != -1))
237 return fd; /* Success */
239 if (errno == ENOENT) {
241 usbi_err(ctx, "File doesn't exist, wait %d ms and try again\n", delay / 1000);
243 /* Wait 10ms for USB device path creation.*/
246 fd = open(path, mode);
247 if (LIKELY(fd != -1))
248 return fd; /* Success */
252 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
253 path, strerror(errno));
254 if (errno == EACCES && mode == O_RDWR)
255 usbi_err(ctx, "libusb requires write access to USB "
260 return LIBUSB_ERROR_ACCESS;
262 return LIBUSB_ERROR_NO_DEVICE;
263 return LIBUSB_ERROR_IO;
266 static struct android_device_priv *_device_priv(struct libusb_device *device);
267 static int _get_usbfs_fd(struct libusb_device *device, mode_t mode, int silent) {
269 struct android_device_priv *dpriv = _device_priv(device);
271 if (LIKELY(dpriv->fd > 0))
274 // fall back to original _get_usbfs_fd function
275 // but this call will fail on Android devices without root
276 #if !defined(__LP64__)
277 usbi_dbg("fd have not set yet. device=%x,fd=%d", (int )device, dpriv->fd);
279 usbi_dbg("fd have not set yet. device=%x,fd=%d", (long )device, dpriv->fd);
281 return __get_usbfs_fd(device, mode, silent);
284 return __get_usbfs_fd(device, mode, silent);
288 static struct android_device_priv *_device_priv(struct libusb_device *dev) {
289 return (struct android_device_priv *) dev->os_priv;
292 static struct android_device_handle_priv *_device_handle_priv(
293 struct libusb_device_handle *handle) {
294 return (struct android_device_handle_priv *) handle->os_priv;
297 /* check dirent for a /dev/usbdev%d.%d name
298 * optionally return bus/device on success */
299 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p) {
302 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
303 return LIBUSB_SUCCESS;
305 usbi_dbg("found: %s", entry->d_name);
313 static int check_usb_vfs(const char *dirname) {
315 struct dirent *entry;
318 dir = opendir(dirname);
320 return LIBUSB_SUCCESS;
322 while ((entry = readdir(dir)) != NULL ) {
323 if (entry->d_name[0] == '.')
326 /* We assume if we find any files that it must be the right place */
335 static const char *find_usbfs_path(void) {
336 const char *path = "/dev/bus/usb";
337 const char *ret = NULL;
339 if (check_usb_vfs(path)) {
342 path = "/proc/bus/usb";
343 if (check_usb_vfs(path))
347 /* look for /dev/usbdev*.* if the normal places fail */
349 struct dirent *entry;
355 while ((entry = readdir(dir)) != NULL ) {
356 if (_is_usbdev_entry(entry, NULL, NULL)) {
357 /* found one; that's enough */
368 usbi_dbg("found usbfs at %s", ret);
373 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
374 * seem to lack it). fall back to REALTIME if we have to. */
375 static clockid_t find_monotonic_clock(void) {
376 #ifdef CLOCK_MONOTONIC
380 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
381 * because it's not available through timerfd */
382 r = clock_gettime(CLOCK_MONOTONIC, &ts);
384 return CLOCK_MONOTONIC;
385 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
388 return CLOCK_REALTIME;
391 static int kernel_version_ge(int major, int minor, int sublevel) {
393 int atoms, kmajor, kminor, ksublevel;
397 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
398 if (UNLIKELY(atoms < 1))
406 /* kmajor == major */
408 return 0 == minor && 0 == sublevel;
414 /* kminor == minor */
416 return 0 == sublevel;
418 return ksublevel >= sublevel;
421 static int op_init2(struct libusb_context *ctx, const char *usbfs) { // XXX
426 if (!usbfs || !strlen(usbfs)) {
427 usbfs_path = find_usbfs_path();
431 if (UNLIKELY(!usbfs_path)) {
432 LOGE("could not find usbfs");
433 usbi_err(ctx, "could not find usbfs");
434 RETURN(LIBUSB_ERROR_OTHER, int);
437 if (monotonic_clkid == -1)
438 monotonic_clkid = find_monotonic_clock();
440 if (supports_flag_bulk_continuation == -1) {
441 /* bulk continuation URB flag available from Linux 2.6.32 */
442 supports_flag_bulk_continuation = kernel_version_ge(2, 6, 32);
443 if (supports_flag_bulk_continuation == -1) {
444 LOGE("error checking for bulk continuation support");
445 usbi_err(ctx, "error checking for bulk continuation support");
446 RETURN(LIBUSB_ERROR_OTHER, int);
450 if (supports_flag_bulk_continuation)
451 usbi_dbg("bulk continuation flag supported");
453 if (-1 == supports_flag_zero_packet) {
454 /* zero length packet URB flag fixed since Linux 2.6.31 */
455 supports_flag_zero_packet = kernel_version_ge(2, 6, 31);
456 if (-1 == supports_flag_zero_packet) {
457 LOGE("error checking for zero length packet support");
458 usbi_err(ctx, "error checking for zero length packet support");
459 RETURN(LIBUSB_ERROR_OTHER, int);
463 if (supports_flag_zero_packet)
464 usbi_dbg("zero length packet flag supported");
466 if (-1 == sysfs_has_descriptors) {
467 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
468 sysfs_has_descriptors = kernel_version_ge(2, 6, 26);
469 if (UNLIKELY(-1 == sysfs_has_descriptors)) {
470 LOGE("error checking for sysfs descriptors");
471 usbi_err(ctx, "error checking for sysfs descriptors");
472 RETURN(LIBUSB_ERROR_OTHER, int);
476 if (-1 == sysfs_can_relate_devices) {
477 /* sysfs has busnum since Linux 2.6.22 */
478 sysfs_can_relate_devices = kernel_version_ge(2, 6, 22);
479 if (UNLIKELY(-1 == sysfs_can_relate_devices)) {
480 LOGE("error checking for sysfs busnum");
481 usbi_err(ctx, "error checking for sysfs busnum");
482 RETURN(LIBUSB_ERROR_OTHER, int);
486 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
487 r = stat(SYSFS_DEVICE_PATH, &statbuf);
488 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
489 usbi_warn(ctx, "sysfs not mounted");
490 sysfs_can_relate_devices = 0;
491 sysfs_has_descriptors = 0;
495 if (sysfs_can_relate_devices)
496 usbi_dbg("sysfs can relate devices");
498 if (sysfs_has_descriptors)
499 usbi_dbg("sysfs has complete descriptors");
501 usbi_mutex_static_lock(&android_hotplug_startstop_lock);
503 if (init_count == 0) {
504 LOGI("start up hotplug event handler");
505 int r = android_start_event_monitor();
506 if (r != LIBUSB_SUCCESS) {
507 LOGE("warning: error starting hotplug event monitor");
508 usbi_err(ctx, "warning: error starting hotplug event monitor");
511 if (r == LIBUSB_SUCCESS) {
512 LOGI("call android_scan_devices");
513 r = android_scan_devices(ctx);
514 if (r == LIBUSB_SUCCESS)
516 else if (init_count == 0)
517 android_stop_event_monitor();
519 LOGE("error starting hotplug event monitor");
520 usbi_err(ctx, "error starting hotplug event monitor");
522 usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
527 static int op_init(struct libusb_context *ctx) {
528 return op_init2(ctx, NULL);
533 usbfs_path = find_usbfs_path();
534 if (UNLIKELY(!usbfs_path)) {
535 usbi_err(ctx, "could not find usbfs");
536 return LIBUSB_ERROR_OTHER;
539 if (monotonic_clkid == -1)
540 monotonic_clkid = find_monotonic_clock();
542 if (supports_flag_bulk_continuation == -1) {
543 /* bulk continuation URB flag available from Linux 2.6.32 */
544 supports_flag_bulk_continuation = kernel_version_ge(2, 6, 32);
545 if (supports_flag_bulk_continuation == -1) {
546 usbi_err(ctx, "error checking for bulk continuation support");
547 return LIBUSB_ERROR_OTHER;
551 if (supports_flag_bulk_continuation)
552 usbi_dbg("bulk continuation flag supported");
554 if (-1 == supports_flag_zero_packet) {
555 /* zero length packet URB flag fixed since Linux 2.6.31 */
556 supports_flag_zero_packet = kernel_version_ge(2, 6, 31);
557 if (-1 == supports_flag_zero_packet) {
558 usbi_err(ctx, "error checking for zero length packet support");
559 return LIBUSB_ERROR_OTHER;
563 if (supports_flag_zero_packet)
564 usbi_dbg("zero length packet flag supported");
566 if (-1 == sysfs_has_descriptors) {
567 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
568 sysfs_has_descriptors = kernel_version_ge(2, 6, 26);
569 if (UNLIKELY(-1 == sysfs_has_descriptors)) {
570 usbi_err(ctx, "error checking for sysfs descriptors");
571 return LIBUSB_ERROR_OTHER;
575 if (-1 == sysfs_can_relate_devices) {
576 /* sysfs has busnum since Linux 2.6.22 */
577 sysfs_can_relate_devices = kernel_version_ge(2, 6, 22);
578 if (UNLIKELY(-1 == sysfs_can_relate_devices)) {
579 usbi_err(ctx, "error checking for sysfs busnum");
580 return LIBUSB_ERROR_OTHER;
584 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
585 r = stat(SYSFS_DEVICE_PATH, &statbuf);
586 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
587 usbi_warn(ctx, "sysfs not mounted");
588 sysfs_can_relate_devices = 0;
589 sysfs_has_descriptors = 0;
593 if (sysfs_can_relate_devices)
594 usbi_dbg("sysfs can relate devices");
596 if (sysfs_has_descriptors)
597 usbi_dbg("sysfs has complete descriptors");
599 usbi_mutex_static_lock(&android_hotplug_startstop_lock);
601 if (init_count == 0) {
602 LOGI("start up hotplug event handler");
603 r = android_start_event_monitor();
605 if (r == LIBUSB_SUCCESS) {
606 r = android_scan_devices(ctx);
607 if (r == LIBUSB_SUCCESS)
609 else if (init_count == 0)
610 android_stop_event_monitor();
612 usbi_err(ctx, "error starting hotplug event monitor");
613 usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
620 static void op_exit(void) {
623 usbi_mutex_static_lock(&android_hotplug_startstop_lock);
624 assert(init_count != 0);
626 /* tear down event handler */
627 (void) android_stop_event_monitor();
629 usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
634 static int android_start_event_monitor(void) {
638 RETURN(LIBUSB_SUCCESS, int);
640 #if defined(USE_UDEV)
641 RETURN(android_udev_start_event_monitor(), int);
643 RETURN(android_netlink_start_event_monitor(), int);
648 static int android_stop_event_monitor(void) {
651 RETURN(LIBUSB_SUCCESS, int);
653 #if defined(USE_UDEV)
654 RETURN(android_udev_stop_event_monitor(), int);
656 RETURN(android_netlink_stop_event_monitor(), int);
661 static int android_scan_devices(struct libusb_context *ctx) {
663 int ret = LIBUSB_SUCCESS;
668 usbi_mutex_static_lock(&android_hotplug_lock);
670 #if defined(USE_UDEV)
671 ret = android_udev_scan_devices(ctx);
673 ret = android_default_scan_devices(ctx);
676 usbi_mutex_static_unlock(&android_hotplug_lock);
681 static void op_hotplug_poll(void) {
686 #if defined(USE_UDEV)
687 android_udev_hotplug_poll();
689 android_netlink_hotplug_poll();
695 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr) {
696 struct android_device_priv *priv = _device_priv(dev);
697 char filename[PATH_MAX];
700 snprintf(filename, PATH_MAX, "%s/%s/%s",
701 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
702 fd = open(filename, O_RDONLY);
703 if (UNLIKELY(fd < 0)) {
704 usbi_err(DEVICE_CTX(dev),
705 "open %s failed ret=%d errno=%d", filename, fd, errno);
706 return LIBUSB_ERROR_IO;
712 /* Note only suitable for attributes which always read >= 0, < 0 is error */
713 static int __read_sysfs_attr(struct libusb_context *ctx, const char *devname,
715 char filename[PATH_MAX];
719 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, devname, attr);
720 f = fopen(filename, "r");
721 if (UNLIKELY(f == NULL)) {
722 if (errno == ENOENT) {
723 /* File doesn't exist. Assume the device has been
724 disconnected (see trac ticket #70). */
725 return LIBUSB_ERROR_NO_DEVICE;
727 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
728 return LIBUSB_ERROR_IO;
731 r = fscanf(f, "%d", &value);
733 if (UNLIKELY(r != 1)) {
734 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
735 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
737 if (UNLIKELY(value < 0)) {
738 usbi_err(ctx, "%s contains a negative value", filename);
739 return LIBUSB_ERROR_IO;
746 static int op_get_raw_descriptor(struct libusb_device *dev,
747 unsigned char *buffer, int *descriptors_len, int *host_endian) {
748 struct android_device_priv *priv = _device_priv(dev);
750 if (!descriptors_len || !host_endian)
751 return LIBUSB_ERROR_INVALID_PARAM;
752 *host_endian = sysfs_has_descriptors ? 0 : 1;
753 if (buffer && (*descriptors_len >= priv->descriptors_len)) {
754 memcpy(buffer, priv->descriptors, priv->descriptors_len);
756 *descriptors_len = priv->descriptors_len;
757 return LIBUSB_SUCCESS;
760 static int op_get_device_descriptor(struct libusb_device *dev,
761 unsigned char *buffer, int *host_endian) {
762 struct android_device_priv *priv = _device_priv(dev);
765 return LIBUSB_ERROR_INVALID_PARAM;
766 *host_endian = sysfs_has_descriptors ? 0 : 1;
767 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
769 return LIBUSB_SUCCESS;
772 /* read the bConfigurationValue for a device */
773 static int sysfs_get_active_config(struct libusb_device *dev, int *config) {
775 char tmp[5] = { 0, 0, 0, 0, 0 };
780 fd = _open_sysfs_attr(dev, "bConfigurationValue");
781 if (UNLIKELY(fd < 0))
784 r = read(fd, tmp, sizeof(tmp));
786 if (UNLIKELY(r < 0)) {
787 usbi_err(DEVICE_CTX(dev),
788 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
789 return LIBUSB_ERROR_IO;
791 usbi_dbg("device unconfigured");
793 return LIBUSB_SUCCESS;
796 if (tmp[sizeof(tmp) - 1] != 0) {
797 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
798 return LIBUSB_ERROR_IO;
799 } else if (tmp[0] == 0) {
800 usbi_err(DEVICE_CTX(dev), "no configuration value?");
801 return LIBUSB_ERROR_IO;
804 num = strtol(tmp, &endptr, 10);
806 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
807 return LIBUSB_ERROR_IO;
811 return LIBUSB_SUCCESS;
814 int android_get_device_address(struct libusb_context *ctx, int detached,
815 uint8_t *busnum, uint8_t *devaddr, const char *dev_node,
816 const char *sys_name) {
819 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
820 /* can't use sysfs to read the bus and device number if the
821 * device has been detached */
822 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
823 if (NULL == dev_node) {
824 return LIBUSB_ERROR_OTHER;
827 /* will this work with all supported kernel versions? */
828 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
829 sscanf(dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
830 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
831 sscanf(dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
834 return LIBUSB_SUCCESS;
837 usbi_dbg("scan %s", sys_name);
839 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
842 if (sysfs_attr > 255)
843 return LIBUSB_ERROR_INVALID_PARAM;
844 *busnum = (uint8_t) sysfs_attr;
846 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
849 if (sysfs_attr > 255)
850 return LIBUSB_ERROR_INVALID_PARAM;
852 *devaddr = (uint8_t) sysfs_attr;
854 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
856 return LIBUSB_SUCCESS;
860 * Return offset of the first descriptor with the given type
861 * return 0 if the buffer is already placed at the specific descriptor.
862 * this is the difference from seek_to_next_descriptor
864 static int seek_to_first_descriptor(struct libusb_context *ctx,
865 uint8_t descriptor_type, unsigned char *buffer, int size) {
866 struct usb_descriptor_header header;
869 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
871 return LIBUSB_ERROR_NOT_FOUND;
873 if (size < LIBUSB_DT_HEADER_SIZE) {
874 usbi_err(ctx, "short descriptor read %d/2", size);
875 return LIBUSB_ERROR_IO;
877 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
879 if (header.bDescriptorType == descriptor_type) // XXX
882 usbi_err(ctx, "bLength overflow by %d bytes", -size);
883 return LIBUSB_ERROR_IO;
887 /* Return offset of the next descriptor with the given type */
888 static int seek_to_next_descriptor(struct libusb_context *ctx,
889 uint8_t descriptor_type, unsigned char *buffer, int size) {
890 struct usb_descriptor_header header;
893 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
895 return LIBUSB_ERROR_NOT_FOUND;
897 if (size < LIBUSB_DT_HEADER_SIZE) {
898 usbi_err(ctx, "short descriptor read %d/2", size);
899 return LIBUSB_ERROR_IO;
901 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
903 if (i && header.bDescriptorType == descriptor_type)
906 usbi_err(ctx, "bLength overflow by %d bytes", -size);
907 return LIBUSB_ERROR_IO;
910 /* Return offset to next config */
911 static int seek_to_next_config(struct libusb_context *ctx,
912 unsigned char *buffer, int size) {
913 struct libusb_config_descriptor config;
914 struct usb_descriptor_header header;
917 return LIBUSB_ERROR_NOT_FOUND;
919 if (size < LIBUSB_DT_HEADER_SIZE) {
920 usbi_err(ctx, "short descriptor read %d/%d",
921 size, LIBUSB_DT_CONFIG_SIZE);
922 return LIBUSB_ERROR_IO;
924 if (size < LIBUSB_DT_CONFIG_SIZE) {
925 usbi_err(ctx, "short descriptor read %d/%d",
926 size, LIBUSB_DT_CONFIG_SIZE);
927 return LIBUSB_ERROR_IO;
930 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
931 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
932 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
933 config.bDescriptorType);
934 return LIBUSB_ERROR_IO;
938 * In usbfs the config descriptors are config.wTotalLength bytes apart,
939 * with any short reads from the device appearing as holes in the file.
941 * In sysfs wTotalLength is ignored, instead the kernel returns a
942 * config descriptor with verified bLength fields, with descriptors
943 * with an invalid bLength removed.
945 if (sysfs_has_descriptors) {
946 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG, buffer, size);
947 if (next == LIBUSB_ERROR_NOT_FOUND)
952 if (next != config.wTotalLength)
953 usbi_warn(ctx, "config length mismatch wTotalLength "
954 "%d real %d", config.wTotalLength, next);
957 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
958 usbi_err(ctx, "invalid wTotalLength %d",
959 config.wTotalLength);
960 return LIBUSB_ERROR_IO;
961 } else if (config.wTotalLength > size) {
962 usbi_warn(ctx, "short descriptor read %d/%d",
963 size, config.wTotalLength);
966 return config.wTotalLength;
970 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
971 uint8_t value, unsigned char **buffer, int *host_endian) {
972 struct libusb_context *ctx = DEVICE_CTX(dev);
973 struct android_device_priv *priv = _device_priv(dev);
974 unsigned char *descriptors = priv->descriptors;
975 int size = priv->descriptors_len, r;
976 struct libusb_config_descriptor *config;
979 /* Unlike the device desc. config descs. are always in raw format */
982 /* Skip device header */
983 descriptors += DEVICE_DESC_LENGTH;
984 size -= DEVICE_DESC_LENGTH;
985 // XXX at this point, we skipped device descriptor only and the next one
986 // will not be a config descriptor. It may be a qualifer descriptor
987 // or other speed config descriptor on some device.
988 // Therefor we need to find the first config descriptor.
989 // FIXME On current implementation, any descriptor other than config descriptor
990 // are skipped if they placed before config descriptor.
991 r = seek_to_first_descriptor(ctx, LIBUSB_DT_CONFIG, descriptors, size);
993 LOGE("could not find config descriptor:r=%d", r);
998 /* Seek till the config is found, or till "EOF" */
1000 register int next = seek_to_next_config(ctx, descriptors, size);
1001 if UNLIKELY(next < 0)
1003 config = (struct libusb_config_descriptor *) descriptors;
1004 if (config->bConfigurationValue == value) {
1005 *buffer = descriptors;
1009 descriptors += next;
1013 static int op_get_active_config_descriptor(struct libusb_device *dev,
1014 unsigned char *buffer, size_t len, int *host_endian) {
1016 unsigned char *config_desc;
1018 if (sysfs_can_relate_devices) {
1019 r = sysfs_get_active_config(dev, &config);
1020 if (UNLIKELY(r < 0))
1023 /* Use cached bConfigurationValue */
1024 struct android_device_priv *priv = _device_priv(dev);
1025 config = priv->active_config;
1028 return LIBUSB_ERROR_NOT_FOUND;
1030 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
1032 if (UNLIKELY(r < 0))
1036 memcpy(buffer, config_desc, len);
1040 static int op_get_config_descriptor(struct libusb_device *dev,
1041 uint8_t config_index, unsigned char *buffer, size_t len,
1043 struct libusb_context *ctx = DEVICE_CTX(dev);
1044 struct android_device_priv *priv = _device_priv(dev);
1045 unsigned char *descriptors = priv->descriptors;
1046 int i, r, size = priv->descriptors_len;
1048 /* Unlike the device desc. config descs. are always in raw format */
1051 /* Skip device header (device descriptor) */
1052 descriptors += DEVICE_DESC_LENGTH;
1053 size -= DEVICE_DESC_LENGTH;
1054 // XXX at this point, we skipped device descriptor only and the next one
1055 // will not be a config descriptor. It may be a qualifer descriptor
1056 // or other speed config descriptor on some device.
1057 // Therefor we need to find the first config descriptor.
1058 // FIXME On current implementation, any descriptor other than config descriptor
1059 // are skipped if they placed before config descriptor.
1060 r = seek_to_first_descriptor(ctx, LIBUSB_DT_CONFIG, descriptors, size);
1061 if UNLIKELY(r < 0) {
1062 LOGE("could not find config descriptor:r=%d", r);
1067 /* Seek till the config is found, or till "EOF" */
1068 for (i = 0; ; i++) {
1069 r = seek_to_next_config(ctx, descriptors, size);
1070 if (UNLIKELY(r < 0)) // if error
1072 if (i == config_index)
1079 memcpy(buffer, descriptors, len);
1083 /* send a control message to retrieve active configuration */
1084 static int usbfs_get_active_config(struct libusb_device *dev, int fd) {
1085 unsigned char active_config = 0;
1088 struct usbfs_ctrltransfer ctrl = {
1089 .bmRequestType = LIBUSB_ENDPOINT_IN,
1090 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
1095 .data = &active_config
1098 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
1099 if (UNLIKELY(r < 0)) {
1100 if (errno == ENODEV)
1101 return LIBUSB_ERROR_NO_DEVICE;
1103 /* we hit this error path frequently with buggy devices :( */
1104 usbi_warn(DEVICE_CTX(dev),
1105 "get_configuration failed ret=%d errno=%d", r, errno);
1106 return LIBUSB_ERROR_IO;
1109 return active_config;
1112 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
1113 uint8_t devaddr, const char *sysfs_dir) {
1115 struct android_device_priv *priv = _device_priv(dev);
1116 struct libusb_context *ctx = DEVICE_CTX(dev);
1117 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
1121 dev->bus_number = busnum;
1122 dev->device_address = devaddr;
1125 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
1126 if (!priv->sysfs_dir)
1127 return LIBUSB_ERROR_NO_MEM;
1128 strcpy(priv->sysfs_dir, sysfs_dir);
1130 /* Note speed can contain 1.5, in this case __read_sysfs_attr
1131 will stop parsing at the '.' and return 1 */
1132 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
1135 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
1136 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
1137 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
1138 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
1140 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
1145 /* cache descriptors in memory */
1146 if (sysfs_has_descriptors) {
1147 fd = _open_sysfs_attr(dev, "descriptors");
1149 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1155 descriptors_size *= 2;
1156 priv->descriptors = usbi_reallocf(priv->descriptors, descriptors_size);
1157 if (UNLIKELY(!priv->descriptors)) {
1159 return LIBUSB_ERROR_NO_MEM;
1161 /* usbfs has holes in the file */
1162 if (!sysfs_has_descriptors) {
1163 memset(priv->descriptors + priv->descriptors_len, 0,
1164 descriptors_size - priv->descriptors_len);
1166 r = read(fd, priv->descriptors + priv->descriptors_len,
1167 descriptors_size - priv->descriptors_len);
1168 if (UNLIKELY(r < 0)) {
1169 usbi_err(ctx, "read descriptor failed ret=%d errno=%d", fd, errno);
1171 return LIBUSB_ERROR_IO;
1173 priv->descriptors_len += r;
1174 } while (priv->descriptors_len == descriptors_size);
1178 if (UNLIKELY(priv->descriptors_len < DEVICE_DESC_LENGTH)) {
1179 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
1180 return LIBUSB_ERROR_IO;
1183 if (sysfs_can_relate_devices)
1184 return LIBUSB_SUCCESS;
1186 /* cache active config */
1187 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1188 if (fd < 0) { // if could not get fd of usbfs with read/write access
1189 /* cannot send a control message to determine the active
1190 * config. just assume the first one is active. */
1191 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1192 "active configuration descriptor");
1193 if (priv->descriptors_len
1194 >= (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1195 struct libusb_config_descriptor config;
1196 usbi_parse_descriptor(priv->descriptors + DEVICE_DESC_LENGTH,
1197 "bbwbbbbb", &config, 0);
1198 priv->active_config = config.bConfigurationValue;
1200 priv->active_config = -1; /* No config dt */
1202 return LIBUSB_SUCCESS;
1204 // if we could get fd of usbfs with read/write access
1205 r = usbfs_get_active_config(dev, fd);
1207 priv->active_config = r;
1209 } else if (r == 0) {
1210 /* some buggy devices have a configuration 0, but we're
1211 * reaching into the corner of a corner case here, so let's
1212 * not support buggy devices in these circumstances.
1213 * stick to the specs: a configuration value of 0 means
1215 usbi_dbg("active cfg 0? assuming unconfigured device");
1216 priv->active_config = -1;
1218 } else if (r == LIBUSB_ERROR_IO) {
1219 /* buggy devices sometimes fail to report their active config.
1220 * assume unconfigured and continue the probing */
1221 usbi_warn(ctx, "couldn't query active configuration, assuming"
1223 priv->active_config = -1;
1225 } /* else r < 0, just return the error code */
1231 static int android_get_parent_info(struct libusb_device *dev,
1232 const char *sysfs_dir) {
1233 struct libusb_context *ctx = DEVICE_CTX(dev);
1234 struct libusb_device *it;
1235 char *parent_sysfs_dir, *tmp;
1236 int ret, add_parent = 1;
1238 /* XXX -- can we figure out the topology when using usbfs? */
1239 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1240 /* either using usbfs or finding the parent of a root hub */
1241 return LIBUSB_SUCCESS;
1244 parent_sysfs_dir = strdup(sysfs_dir);
1245 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1246 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1247 dev->port_number = atoi(tmp + 1);
1250 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1252 free(parent_sysfs_dir);
1253 return LIBUSB_SUCCESS;
1256 /* is the parent a root hub? */
1257 if (NULL == strchr(parent_sysfs_dir, '-')) {
1258 tmp = parent_sysfs_dir;
1259 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
1262 return LIBUSB_ERROR_NO_MEM;
1267 /* find the parent in the context */
1268 usbi_mutex_lock(&ctx->usb_devs_lock);
1269 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device)
1271 struct android_device_priv *priv = _device_priv(it);
1272 if (0 == strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
1273 dev->parent_dev = libusb_ref_device(it);
1277 usbi_mutex_unlock(&ctx->usb_devs_lock);
1279 if (!dev->parent_dev && add_parent) {
1280 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1282 sysfs_scan_device(ctx, parent_sysfs_dir);
1287 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1288 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1290 free(parent_sysfs_dir);
1292 return LIBUSB_SUCCESS;
1295 static int android_initialize_device(struct libusb_device *dev,
1296 uint8_t busnum, uint8_t devaddr, int fd) {
1300 struct android_device_priv *priv = _device_priv(dev);
1301 struct libusb_context *ctx = DEVICE_CTX(dev);
1302 uint8_t desc[4096]; // max descriptor size is 4096 bytes
1306 dev->bus_number = busnum;
1307 dev->device_address = devaddr;
1309 LOGD("cache descriptors in memory");
1311 priv->descriptors_len = 0;
1313 memset(desc, 0, sizeof(desc));
1314 if (!lseek(fd, 0, SEEK_SET)) {
1315 // ディスクリプタを読み込んでローカルキャッシュする
1316 int length = read(fd, desc, sizeof(desc));
1317 LOGD("Device::init read returned %d errno %d\n", length, errno);
1320 priv->descriptors = usbi_reallocf(priv->descriptors, length);
1321 if (UNLIKELY(!priv->descriptors)) {
1322 RETURN(LIBUSB_ERROR_NO_MEM, int);
1324 priv->descriptors_len = length;
1325 memcpy(priv->descriptors, desc, length);
1329 if (UNLIKELY(priv->descriptors_len < DEVICE_DESC_LENGTH)) {
1330 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
1331 LOGE("short descriptor read (%d)", priv->descriptors_len);
1332 RETURN(LIBUSB_ERROR_IO, int);
1335 if (fd < 0) { // if could not get fd of usbfs with read/write access
1336 /* cannot send a control message to determine the active
1337 * config. just assume the first one is active. */
1338 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1339 "active configuration descriptor");
1340 if (priv->descriptors_len
1341 >= (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1342 struct libusb_config_descriptor config;
1343 usbi_parse_descriptor(priv->descriptors + DEVICE_DESC_LENGTH,
1344 "bbwbbbbb", &config, 0);
1345 priv->active_config = config.bConfigurationValue;
1347 priv->active_config = -1; /* No config dt */
1349 RETURN(LIBUSB_SUCCESS, int);
1351 // if we could get fd of usbfs with read/write access
1352 r = usbfs_get_active_config(dev, fd);
1354 priv->active_config = r;
1356 } else if (r == 0) {
1357 /* some buggy devices have a configuration 0, but we're
1358 * reaching into the corner of a corner case here, so let's
1359 * not support buggy devices in these circumstances.
1360 * stick to the specs: a configuration value of 0 means
1362 usbi_dbg("active cfg 0? assuming unconfigured device");
1363 priv->active_config = -1;
1365 } else if (r == LIBUSB_ERROR_IO) {
1366 /* buggy devices sometimes fail to report their active config.
1367 * assume unconfigured and continue the probing */
1368 usbi_warn(ctx, "couldn't query active configuration, assuming"
1370 priv->active_config = -1;
1372 } /* else r < 0, just return the error code */
1377 int android_generate_device(struct libusb_context *ctx, struct libusb_device **dev,
1378 int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
1382 unsigned long session_id;
1386 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1387 * will be reused. instead we should add a simple sysfs attribute with
1389 session_id = busnum << 8 | devaddr;
1390 LOGD("allocating new device for %d/%d (session %ld)", busnum, devaddr, session_id);
1391 *dev = usbi_alloc_device(ctx, session_id); // この時点で参照カウンタ=1
1392 if (UNLIKELY(!dev)) {
1393 RETURN(LIBUSB_ERROR_NO_MEM, int);
1396 r = android_initialize_device(*dev, busnum, devaddr, fd);
1397 if (UNLIKELY(r < 0)) {
1398 LOGE("initialize_device failed: ret=%d", r);
1401 r = usbi_sanitize_device(*dev);
1402 if (UNLIKELY(r < 0)) {
1403 LOGE("usbi_sanitize_device failed: ret=%d", r);
1408 if (UNLIKELY(r < 0)) {
1409 libusb_unref_device(*dev); // ここで参照カウンタが0になって破棄される
1412 usbi_connect_device(*dev);
1419 int android_enumerate_device(struct libusb_context *ctx, uint8_t busnum,
1420 uint8_t devaddr, const char *sysfs_dir) {
1422 unsigned long session_id;
1423 struct libusb_device *dev;
1426 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1427 * will be reused. instead we should add a simple sysfs attribute with
1429 session_id = busnum << 8 | devaddr;
1430 usbi_dbg("busnum %d devaddr %d session_id %ld",
1431 busnum, devaddr, session_id);
1433 dev = usbi_get_device_by_session_id(ctx, session_id);
1435 /* device already exists in the context */
1436 usbi_dbg("session_id %ld already exists", session_id);
1437 libusb_unref_device(dev);
1438 return LIBUSB_SUCCESS;
1441 usbi_dbg("allocating new device for %d/%d (session %ld)",
1442 busnum, devaddr, session_id);
1443 dev = usbi_alloc_device(ctx, session_id);
1445 return LIBUSB_ERROR_NO_MEM;
1447 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1448 if (UNLIKELY(r < 0))
1450 r = usbi_sanitize_device(dev);
1451 if (UNLIKELY(r < 0))
1454 r = android_get_parent_info(dev, sysfs_dir);
1455 if (UNLIKELY(r < 0))
1458 if (UNLIKELY(r < 0))
1459 libusb_unref_device(dev);
1461 usbi_connect_device(dev);
1466 void android_hotplug_enumerate(uint8_t busnum, uint8_t devaddr,
1467 const char *sys_name) {
1468 struct libusb_context *ctx;
1470 usbi_mutex_static_lock(&active_contexts_lock);
1471 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context)
1473 android_enumerate_device(ctx, busnum, devaddr, sys_name);
1475 usbi_mutex_static_unlock(&active_contexts_lock);
1478 void android_device_disconnected(uint8_t busnum, uint8_t devaddr,
1479 const char *sys_name) {
1480 struct libusb_context *ctx;
1481 struct libusb_device *dev;
1482 unsigned long session_id = busnum << 8 | devaddr;
1484 usbi_mutex_static_lock(&active_contexts_lock);
1485 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context)
1487 dev = usbi_get_device_by_session_id(ctx, session_id);
1489 usbi_disconnect_device(dev);
1490 libusb_unref_device(dev);
1492 usbi_dbg("device not found for session %x", session_id);
1495 usbi_mutex_static_unlock(&active_contexts_lock);
1498 #if !defined(USE_UDEV)
1499 /* open a bus directory and adds all discovered devices to the context */
1500 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum) {
1502 char dirpath[PATH_MAX];
1503 struct dirent *entry;
1504 int r = LIBUSB_ERROR_IO;
1506 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1507 usbi_dbg("%s", dirpath);
1508 dir = opendir(dirpath);
1509 if (UNLIKELY(!dir)) {
1510 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1511 /* FIXME: should handle valid race conditions like hub unplugged
1512 * during directory iteration - this is not an error */
1516 while ((entry = readdir(dir))) {
1519 if (entry->d_name[0] == '.')
1522 devaddr = atoi(entry->d_name);
1524 usbi_dbg("unknown dir entry %s", entry->d_name);
1528 if (android_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1529 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1540 static int usbfs_get_device_list(struct libusb_context *ctx) {
1541 struct dirent *entry;
1542 DIR *buses = opendir(usbfs_path);
1546 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1547 return LIBUSB_ERROR_IO;
1550 while ((entry = readdir(buses))) {
1553 if (entry->d_name[0] == '.')
1558 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1561 r = android_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1562 if (UNLIKELY(r < 0)) {
1563 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1567 busnum = atoi(entry->d_name);
1568 if (UNLIKELY(busnum == 0)) {
1569 usbi_dbg("unknown dir entry %s", entry->d_name);
1573 r = usbfs_scan_busdir(ctx, busnum);
1574 if (UNLIKELY(r < 0))
1585 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname) {
1586 uint8_t busnum, devaddr;
1589 ret = android_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname);
1590 if (UNLIKELY(LIBUSB_SUCCESS != ret)) {
1594 return android_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff, devname);
1597 #if !defined(USE_UDEV)
1598 static int sysfs_get_device_list(struct libusb_context *ctx) {
1599 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1600 struct dirent *entry;
1601 int r = LIBUSB_ERROR_IO;
1603 if (UNLIKELY(!devices)) {
1604 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1608 while ((entry = readdir(devices))) {
1609 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1610 || strchr(entry->d_name, ':'))
1613 if (sysfs_scan_device(ctx, entry->d_name)) {
1614 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1625 static int android_default_scan_devices(struct libusb_context *ctx) {
1626 /* we can retrieve device list and descriptors from sysfs or usbfs.
1627 * sysfs is preferable, because if we use usbfs we end up resuming
1628 * any autosuspended USB devices. however, sysfs is not available
1629 * everywhere, so we need a usbfs fallback too.
1631 * as described in the "sysfs vs usbfs" comment at the top of this
1632 * file, sometimes we have sysfs but not enough information to
1633 * relate sysfs devices to usbfs nodes. op_init() determines the
1634 * adequacy of sysfs and sets sysfs_can_relate_devices.
1636 if (sysfs_can_relate_devices != 0)
1637 return sysfs_get_device_list(ctx);
1639 return usbfs_get_device_list(ctx);
1643 // this function is mainly for Android
1644 // because native code can not open USB device on Android when without root
1645 // so we need to defer real open/close operation to Java code
1646 static int op_set_device_fd(struct libusb_device *device, int fd) {
1647 struct android_device_priv *dpriv = _device_priv(device);
1649 return LIBUSB_SUCCESS;
1652 static int op_open(struct libusb_device_handle *handle) {
1653 struct android_device_handle_priv *hpriv = _device_handle_priv(handle);
1656 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1657 if (hpriv->fd < 0) {
1658 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1659 /* device will still be marked as attached if hotplug monitor thread
1660 * hasn't processed remove event yet */
1661 usbi_mutex_static_lock(&android_hotplug_lock);
1662 if (handle->dev->attached) {
1663 usbi_dbg("open failed with no device, but device still attached");
1664 android_device_disconnected(handle->dev->bus_number,
1665 handle->dev->device_address, NULL);
1667 usbi_mutex_static_unlock(&android_hotplug_lock);
1672 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1673 if (UNLIKELY(r < 0)) {
1674 if (errno == ENOTTY)
1675 usbi_dbg("getcap not available");
1677 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1679 if (supports_flag_zero_packet)
1680 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1681 if (supports_flag_bulk_continuation)
1682 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1685 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1688 static void op_close(struct libusb_device_handle *dev_handle) {
1689 int fd = _device_handle_priv(dev_handle)->fd;
1690 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1692 // We can not (re)open USB device in the native code on no-rooted Android devices
1693 // so keep open and defer real open/close operation on Java side
1698 static int op_get_configuration(struct libusb_device_handle *handle,
1702 if (sysfs_can_relate_devices) {
1703 r = sysfs_get_active_config(handle->dev, config);
1705 r = usbfs_get_active_config(handle->dev,
1706 _device_handle_priv(handle)->fd);
1708 if (UNLIKELY(r < 0))
1711 if (*config == -1) {
1712 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1716 return LIBUSB_SUCCESS;
1719 static int op_set_configuration(struct libusb_device_handle *handle, int config) {
1720 struct android_device_priv *priv = _device_priv(handle->dev);
1721 const int fd = _device_handle_priv(handle)->fd;
1722 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1724 if (errno == EINVAL) {
1725 return LIBUSB_ERROR_NOT_FOUND;
1726 } else if (errno == EBUSY) {
1727 return LIBUSB_ERROR_BUSY;
1728 } else if (errno == ENODEV) {
1729 return LIBUSB_ERROR_NO_DEVICE;
1731 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1732 return LIBUSB_ERROR_OTHER;
1735 /* update our cached active config descriptor */
1736 priv->active_config = config;
1738 return LIBUSB_SUCCESS;
1741 static int claim_interface(struct libusb_device_handle *handle, int iface) {
1745 const int fd = _device_handle_priv(handle)->fd;
1746 LOGD("interface=%d, fd=%d", iface, fd);
1748 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1750 if (errno == ENOENT) {
1751 RETURN(LIBUSB_ERROR_NOT_FOUND, int);
1752 } else if (errno == EBUSY) {
1753 RETURN(LIBUSB_ERROR_BUSY, int);
1754 } else if (errno == ENODEV) {
1755 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1757 LOGE("claim interface failed, error %d errno %d", r, errno);
1758 RETURN(LIBUSB_ERROR_OTHER, int);
1761 RETURN(LIBUSB_SUCCESS, int);
1764 static int release_interface(struct libusb_device_handle *handle, int iface) {
1768 const int fd = _device_handle_priv(handle)->fd;
1769 LOGD("interface=%d, fd=%d", iface, fd);
1771 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1773 if (errno == ENODEV) {
1774 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1776 LOGE("release interface failed, error %d errno %d", r, errno);
1777 RETURN(LIBUSB_ERROR_OTHER, int);
1780 RETURN(LIBUSB_SUCCESS, int);
1783 static int op_set_interface(struct libusb_device_handle *handle, int iface, int altsetting) {
1787 const int fd = _device_handle_priv(handle)->fd;
1788 struct usbfs_setinterface setintf;
1791 setintf.interface = iface;
1792 setintf.altsetting = altsetting;
1793 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1795 if (errno == EINVAL) {
1796 RETURN(LIBUSB_ERROR_NOT_FOUND, int);
1797 } else if (errno == ENODEV) {
1798 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1800 usbi_err(HANDLE_CTX(handle),
1801 "setintf failed error %d errno %d", r, errno);
1802 RETURN(LIBUSB_ERROR_OTHER, int);
1805 RETURN(LIBUSB_SUCCESS, int);
1808 static int op_clear_halt(struct libusb_device_handle *handle,
1809 unsigned char endpoint) {
1810 const int fd = _device_handle_priv(handle)->fd;
1811 unsigned int _endpoint = endpoint;
1812 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1814 if (errno == ENOENT)
1815 return LIBUSB_ERROR_NOT_FOUND;
1816 else if (errno == ENODEV)
1817 return LIBUSB_ERROR_NO_DEVICE;
1819 usbi_err(HANDLE_CTX(handle),
1820 "clear_halt failed error %d errno %d", r, errno);
1821 return LIBUSB_ERROR_OTHER;
1824 return LIBUSB_SUCCESS;
1827 static int op_reset_device(struct libusb_device_handle *handle) {
1828 const int fd = _device_handle_priv(handle)->fd;
1831 /* Doing a device reset will cause the usbfs driver to get unbound
1832 from any interfaces it is bound to. By voluntarily unbinding
1833 the usbfs driver ourself, we stop the kernel from rebinding
1834 the interface after reset (which would end up with the interface
1835 getting bound to the in kernel driver if any). */
1836 for (i = 0; i < USB_MAXINTERFACES; i++) {
1837 if (handle->claimed_interfaces & (1L << i)) {
1838 release_interface(handle, i);
1842 usbi_mutex_lock(&handle->lock);
1843 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1845 if (errno == ENODEV) {
1846 ret = LIBUSB_ERROR_NOT_FOUND;
1850 usbi_err(HANDLE_CTX(handle),
1851 "reset failed error %d errno %d", r, errno);
1852 ret = LIBUSB_ERROR_OTHER;
1856 /* And re-claim any interfaces which were claimed before the reset */
1857 for (i = 0; i < USB_MAXINTERFACES; i++) {
1858 if (handle->claimed_interfaces & (1L << i)) {
1860 * A driver may have completed modprobing during
1861 * IOCTL_USBFS_RESET, and bound itself as soon as
1862 * IOCTL_USBFS_RESET released the device lock
1864 r = detach_kernel_driver_and_claim(handle, i);
1866 usbi_warn(HANDLE_CTX(handle),
1867 "failed to re-claim interface %d after reset: %s",
1868 i, libusb_error_name(r));
1869 handle->claimed_interfaces &= ~(1L << i);
1870 ret = LIBUSB_ERROR_NOT_FOUND;
1875 usbi_mutex_unlock(&handle->lock);
1879 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1880 uint32_t num_streams, unsigned char *endpoints, int num_endpoints) {
1881 const int fd = _device_handle_priv(handle)->fd;
1883 struct usbfs_streams *streams;
1885 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1886 return LIBUSB_ERROR_INVALID_PARAM;
1888 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1890 return LIBUSB_ERROR_NO_MEM;
1892 streams->num_streams = num_streams;
1893 streams->num_eps = num_endpoints;
1894 memcpy(streams->eps, endpoints, num_endpoints);
1896 r = ioctl(fd, req, streams);
1901 if (errno == ENOTTY)
1902 return LIBUSB_ERROR_NOT_SUPPORTED;
1903 else if (errno == EINVAL)
1904 return LIBUSB_ERROR_INVALID_PARAM;
1905 else if (errno == ENODEV)
1906 return LIBUSB_ERROR_NO_DEVICE;
1908 usbi_err(HANDLE_CTX(handle),
1909 "streams-ioctl failed error %d errno %d", r, errno);
1910 return LIBUSB_ERROR_OTHER;
1915 static int op_alloc_streams(struct libusb_device_handle *handle,
1916 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1918 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1919 num_streams, endpoints, num_endpoints);
1922 static int op_free_streams(struct libusb_device_handle *handle,
1923 unsigned char *endpoints, int num_endpoints)
1925 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1926 endpoints, num_endpoints);
1929 static int op_kernel_driver_active(struct libusb_device_handle *handle, int interface) {
1930 const int fd = _device_handle_priv(handle)->fd;
1931 struct usbfs_getdriver getdrv;
1934 getdrv.interface = interface;
1935 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1937 if (errno == ENODATA)
1938 return LIBUSB_SUCCESS;
1939 else if (errno == ENODEV)
1940 return LIBUSB_ERROR_NO_DEVICE;
1942 usbi_err(HANDLE_CTX(handle),
1943 "get driver failed error %d errno %d", r, errno);
1944 return LIBUSB_ERROR_OTHER;
1947 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1950 static int op_detach_kernel_driver(struct libusb_device_handle *handle, int interface) {
1951 const int fd = _device_handle_priv(handle)->fd;
1952 struct usbfs_ioctl command;
1953 struct usbfs_getdriver getdrv;
1956 command.ifno = interface;
1957 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1958 command.data = NULL;
1960 getdrv.interface = interface;
1961 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1962 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1963 return LIBUSB_ERROR_NOT_FOUND;
1965 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1967 if (errno == ENODATA)
1968 return LIBUSB_ERROR_NOT_FOUND;
1969 else if (errno == EINVAL)
1970 return LIBUSB_ERROR_INVALID_PARAM;
1971 else if (errno == ENODEV)
1972 return LIBUSB_ERROR_NO_DEVICE;
1974 usbi_err(HANDLE_CTX(handle),
1975 "detach failed error %d errno %d", r, errno);
1976 return LIBUSB_ERROR_OTHER;
1979 return LIBUSB_SUCCESS;
1982 static int op_attach_kernel_driver(struct libusb_device_handle *handle, int interface) {
1983 const int fd = _device_handle_priv(handle)->fd;
1984 struct usbfs_ioctl command;
1987 command.ifno = interface;
1988 command.ioctl_code = IOCTL_USBFS_CONNECT;
1989 command.data = NULL;
1991 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1992 if (UNLIKELY(r < 0)) {
1993 if (errno == ENODATA)
1994 return LIBUSB_ERROR_NOT_FOUND;
1995 else if (errno == EINVAL)
1996 return LIBUSB_ERROR_INVALID_PARAM;
1997 else if (errno == ENODEV)
1998 return LIBUSB_ERROR_NO_DEVICE;
1999 else if (errno == EBUSY)
2000 return LIBUSB_ERROR_BUSY;
2002 usbi_err(HANDLE_CTX(handle),
2003 "attach failed error %d errno %d", r, errno);
2004 return LIBUSB_ERROR_OTHER;
2005 } else if (UNLIKELY(r == 0)) {
2006 return LIBUSB_ERROR_NOT_FOUND;
2009 return LIBUSB_SUCCESS;
2012 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle, int interface) {
2016 const int fd = _device_handle_priv(handle)->fd;
2017 struct usbfs_disconnect_claim dc;
2020 dc.interface = interface;
2021 strcpy(dc.driver, "usbfs");
2022 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
2023 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
2024 if (r == 0 || (r != 0 && errno != ENOTTY)) {
2026 RETURN(LIBUSB_SUCCESS, int);
2031 RETURN(LIBUSB_ERROR_BUSY, int);
2033 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
2035 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
2037 usbi_err(HANDLE_CTX(handle),
2038 "disconnect-and-claim failed errno %d", errno);
2039 RETURN(LIBUSB_ERROR_OTHER, int);
2042 /* Fallback code for kernels which don't support the
2043 disconnect-and-claim ioctl */
2044 r = op_detach_kernel_driver(handle, interface);
2045 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND) {
2049 r = claim_interface(handle, interface);
2053 static int op_claim_interface(struct libusb_device_handle *handle, int iface) {
2054 if (handle->auto_detach_kernel_driver)
2055 return detach_kernel_driver_and_claim(handle, iface);
2057 return claim_interface(handle, iface);
2060 static int op_release_interface(struct libusb_device_handle *handle, int iface) {
2063 r = release_interface(handle, iface);
2067 if (handle->auto_detach_kernel_driver)
2068 op_attach_kernel_driver(handle, iface);
2070 return LIBUSB_SUCCESS;
2073 static void op_destroy_device(struct libusb_device *dev) {
2074 struct android_device_priv *priv = _device_priv(dev);
2075 if (priv->descriptors)
2076 free(priv->descriptors);
2077 if (priv->sysfs_dir)
2078 free(priv->sysfs_dir);
2081 /* URBs are discarded in reverse order of submission to avoid races. */
2082 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one) {
2085 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2086 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2087 struct android_device_handle_priv *dpriv = _device_handle_priv(transfer->dev_handle);
2089 struct usbfs_urb *urb;
2091 for (i = last_plus_one - 1; i >= first; i--) {
2092 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
2093 urb = tpriv->iso_urbs[i];
2095 urb = &tpriv->urbs[i];
2097 // XXX this function call may always fail on non-rooted Android devices with errno=22(EINVAL)...
2098 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
2101 if (EINVAL == errno) {
2102 usbi_dbg("URB not found --> assuming ready to be reaped");
2103 if (i == (last_plus_one - 1))
2104 ret = LIBUSB_ERROR_NOT_FOUND;
2105 } else if (ENODEV == errno) {
2106 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
2107 ret = LIBUSB_ERROR_NO_DEVICE;
2109 usbi_warn(TRANSFER_CTX(transfer),
2110 "unrecognised discard errno %d", errno);
2111 ret = LIBUSB_ERROR_OTHER;
2117 static void free_iso_urbs(struct android_transfer_priv *tpriv) {
2119 for (i = 0; i < tpriv->num_urbs; i++) {
2120 struct usbfs_urb *urb = tpriv->iso_urbs[i];
2126 free(tpriv->iso_urbs);
2127 tpriv->iso_urbs = NULL;
2130 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
2132 struct libusb_transfer *transfer
2133 = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2134 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2135 struct android_device_handle_priv *dpriv
2136 = _device_handle_priv(transfer->dev_handle);
2137 struct usbfs_urb *urbs;
2138 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
2139 == LIBUSB_ENDPOINT_OUT;
2140 int bulk_buffer_len, use_bulk_continuation;
2145 if (UNLIKELY(tpriv->urbs))
2146 return LIBUSB_ERROR_BUSY;
2148 if (UNLIKELY(is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
2149 && !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
2150 return LIBUSB_ERROR_NOT_SUPPORTED;
2153 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
2154 * around this by splitting large transfers into 16k blocks, and then
2155 * submit all urbs at once. it would be simpler to submit one urb at
2156 * a time, but there is a big performance gain doing it this way.
2158 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
2159 * using arbritary large transfers can still be a bad idea though, as
2160 * the kernel needs to allocate physical contiguous memory for this,
2161 * which may fail for large buffers.
2163 * The kernel solves this problem by splitting the transfer into
2164 * blocks itself when the host-controller is scatter-gather capable
2165 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
2167 * Last, there is the issue of short-transfers when splitting, for
2168 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
2169 * is needed, but this is not always available.
2171 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
2172 /* Good! Just submit everything in one go */
2173 bulk_buffer_len = transfer->length ? transfer->length : 1;
2174 use_bulk_continuation = 0;
2175 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
2176 /* Split the transfers and use bulk-continuation to
2177 avoid issues with short-transfers */
2178 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2179 use_bulk_continuation = 1;
2180 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
2181 /* Don't split, assume the kernel can alloc the buffer
2182 (otherwise the submit will fail with -ENOMEM) */
2183 bulk_buffer_len = transfer->length ? transfer->length : 1;
2184 use_bulk_continuation = 0;
2186 /* Bad, splitting without bulk-continuation, short transfers
2187 which end before the last urb will not work reliable! */
2188 /* Note we don't warn here as this is "normal" on kernels <
2189 2.6.32 and not a problem for most applications */
2190 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2191 use_bulk_continuation = 0;
2194 int num_urbs = transfer->length / bulk_buffer_len;
2195 int last_urb_partial = 0;
2197 if (transfer->length == 0) {
2199 } else if ((transfer->length % bulk_buffer_len) > 0) {
2200 last_urb_partial = 1;
2203 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2204 alloc_size = num_urbs * sizeof(struct usbfs_urb);
2205 urbs = calloc(1, alloc_size);
2206 if (UNLIKELY(!urbs))
2207 return LIBUSB_ERROR_NO_MEM;
2209 tpriv->num_urbs = num_urbs;
2210 tpriv->num_retired = 0;
2211 tpriv->reap_action = NORMAL;
2212 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2214 for (i = 0; i < num_urbs; i++) {
2215 struct usbfs_urb *urb = &urbs[i];
2216 urb->usercontext = itransfer;
2217 switch (transfer->type) {
2218 case LIBUSB_TRANSFER_TYPE_BULK:
2219 urb->type = USBFS_URB_TYPE_BULK;
2222 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2223 urb->type = USBFS_URB_TYPE_BULK;
2224 urb->stream_id = itransfer->stream_id;
2226 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2227 urb->type = USBFS_URB_TYPE_INTERRUPT;
2230 urb->endpoint = transfer->endpoint;
2231 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2232 /* don't set the short not ok flag for the last URB */
2233 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2234 urb->flags = USBFS_URB_SHORT_NOT_OK;
2235 if (i == num_urbs - 1 && last_urb_partial)
2236 urb->buffer_length = transfer->length % bulk_buffer_len;
2237 else if (transfer->length == 0)
2238 urb->buffer_length = 0;
2240 urb->buffer_length = bulk_buffer_len;
2242 if (i > 0 && use_bulk_continuation)
2243 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2245 /* we have already checked that the flag is supported */
2246 if (is_out && i == num_urbs - 1
2247 && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2248 urb->flags |= USBFS_URB_ZERO_PACKET;
2250 dump_urb(i, dpriv->fd, urb);
2252 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2253 if (UNLIKELY(r < 0)) {
2254 if (errno == ENODEV) {
2255 r = LIBUSB_ERROR_NO_DEVICE;
2257 usbi_err(TRANSFER_CTX(transfer),
2258 "submiturb failed error %d errno=%d", r, errno);
2259 r = LIBUSB_ERROR_IO;
2262 /* if the first URB submission fails, we can simply free up and
2263 * return failure immediately. */
2264 if (UNLIKELY(i == 0)) {
2265 usbi_dbg("first URB failed, easy peasy");
2271 /* if it's not the first URB that failed, the situation is a bit
2272 * tricky. we may need to discard all previous URBs. there are
2274 * - discarding is asynchronous - discarded urbs will be reaped
2275 * later. the user must not have freed the transfer when the
2276 * discarded URBs are reaped, otherwise libusb will be using
2278 * - the earlier URBs may have completed successfully and we do
2279 * not want to throw away any data.
2280 * - this URB failing may be no error; EREMOTEIO means that
2281 * this transfer simply didn't need all the URBs we submitted
2282 * so, we report that the transfer was submitted successfully and
2283 * in case of error we discard all previous URBs. later when
2284 * the final reap completes we can report error to the user,
2285 * or success if an earlier URB was completed successfully.
2287 tpriv->reap_action =
2288 EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2290 /* The URBs we haven't submitted yet we count as already
2292 tpriv->num_retired += num_urbs - i;
2294 /* If we completed short then don't try to discard. */
2295 if (COMPLETED_EARLY == tpriv->reap_action)
2296 return LIBUSB_SUCCESS;
2298 discard_urbs(itransfer, 0, i);
2300 usbi_dbg("reporting successful submission but waiting for %d "
2301 "discards before reporting error", i);
2302 return LIBUSB_SUCCESS;
2306 return LIBUSB_SUCCESS;
2309 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
2310 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2311 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2312 struct android_device_handle_priv *dpriv = _device_handle_priv(transfer->dev_handle);
2313 struct usbfs_urb **urbs;
2315 const int num_packets = transfer->num_iso_packets;
2317 int this_urb_len = 0;
2319 int packet_offset = 0;
2320 unsigned int packet_len;
2321 unsigned char *urb_buffer = transfer->buffer;
2323 if (UNLIKELY(tpriv->iso_urbs))
2324 return LIBUSB_ERROR_BUSY;
2326 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
2327 * into smaller units to meet such restriction, then fire off all the
2328 * units at once. it would be simpler if we just fired one unit at a time,
2329 * but there is a big performance gain through doing it this way.
2331 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
2332 * using arbritary large transfers is still be a bad idea though, as
2333 * the kernel needs to allocate physical contiguous memory for this,
2334 * which may fail for large buffers.
2337 /* calculate how many URBs we need */
2338 for (i = 0; i < num_packets; i++) {
2339 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
2340 packet_len = transfer->iso_packet_desc[i].length;
2342 if (packet_len > space_remaining) {
2344 this_urb_len = packet_len;
2346 this_urb_len += packet_len;
2349 usbi_dbg("need %d of 32k URBs for transfer", num_urbs);
2351 alloc_size = num_urbs * sizeof(*urbs);
2352 urbs = calloc(1, alloc_size);
2353 if (UNLIKELY(!urbs))
2354 return LIBUSB_ERROR_NO_MEM;
2356 tpriv->iso_urbs = urbs;
2357 tpriv->num_urbs = num_urbs;
2358 tpriv->num_retired = 0;
2359 tpriv->reap_action = NORMAL;
2360 tpriv->iso_packet_offset = 0;
2362 /* allocate + initialize each URB with the correct number of packets */
2363 for (i = 0; i < num_urbs; i++) {
2364 struct usbfs_urb *urb;
2365 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2366 int urb_packet_offset = 0;
2367 unsigned char *urb_buffer_orig = urb_buffer;
2371 /* swallow up all the packets we can fit into this URB */
2372 while (packet_offset < num_packets) {
2373 packet_len = transfer->iso_packet_desc[packet_offset].length;
2374 if (packet_len <= space_remaining_in_urb) {
2376 urb_packet_offset++;
2378 space_remaining_in_urb -= packet_len;
2379 urb_buffer += packet_len;
2381 /* it can't fit, save it for the next URB */
2386 alloc_size = sizeof(*urb)
2387 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2388 urb = calloc(1, alloc_size);
2389 if (UNLIKELY(!urb)) {
2390 free_iso_urbs(tpriv);
2391 return LIBUSB_ERROR_NO_MEM;
2395 /* populate packet lengths */
2396 for (j = 0, k = packet_offset - urb_packet_offset;
2397 k < packet_offset; k++, j++) {
2398 packet_len = transfer->iso_packet_desc[k].length;
2399 urb->iso_frame_desc[j].length = packet_len;
2402 urb->usercontext = itransfer;
2403 urb->type = USBFS_URB_TYPE_ISO;
2404 /* FIXME: interface for non-ASAP data? */
2405 urb->flags = USBFS_URB_ISO_ASAP;
2406 urb->endpoint = transfer->endpoint;
2407 urb->number_of_packets = urb_packet_offset;
2408 urb->buffer = urb_buffer_orig;
2412 for (i = 0; i < num_urbs; i++) {
2413 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2414 if (UNLIKELY(r < 0)) {
2415 if (errno == ENODEV) {
2416 r = LIBUSB_ERROR_NO_DEVICE;
2418 usbi_err(TRANSFER_CTX(transfer),
2419 "submiturb failed error %d errno=%d", r, errno);
2420 r = LIBUSB_ERROR_IO;
2423 /* if the first URB submission fails, we can simply free up and
2424 * return failure immediately. */
2425 if (UNLIKELY(i == 0)) {
2426 usbi_dbg("first URB failed, easy peasy");
2427 free_iso_urbs(tpriv);
2431 /* if it's not the first URB that failed, the situation is a bit
2432 * tricky. we must discard all previous URBs. there are
2434 * - discarding is asynchronous - discarded urbs will be reaped
2435 * later. the user must not have freed the transfer when the
2436 * discarded URBs are reaped, otherwise libusb will be using
2438 * - the earlier URBs may have completed successfully and we do
2439 * not want to throw away any data.
2440 * so, in this case we discard all the previous URBs BUT we report
2441 * that the transfer was submitted successfully. then later when
2442 * the final discard completes we can report error to the user.
2444 tpriv->reap_action = SUBMIT_FAILED;
2446 /* The URBs we haven't submitted yet we count as already
2448 tpriv->num_retired = num_urbs - i;
2449 discard_urbs(itransfer, 0, i);
2451 usbi_dbg("reporting successful submission but waiting for %d "
2452 "discards before reporting error", i);
2453 return LIBUSB_SUCCESS;
2457 return LIBUSB_SUCCESS;
2460 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2461 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2462 struct libusb_transfer *transfer
2463 = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2464 struct android_device_handle_priv *dpriv
2465 = _device_handle_priv(transfer->dev_handle);
2466 struct usbfs_urb *urb;
2469 if (UNLIKELY(tpriv->urbs))
2470 return LIBUSB_ERROR_BUSY;
2472 if (UNLIKELY(transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH))
2473 return LIBUSB_ERROR_INVALID_PARAM;
2475 urb = calloc(1, sizeof(struct usbfs_urb));
2477 return LIBUSB_ERROR_NO_MEM;
2479 tpriv->num_urbs = 1;
2480 tpriv->reap_action = NORMAL;
2482 urb->usercontext = itransfer;
2483 urb->type = USBFS_URB_TYPE_CONTROL;
2484 urb->endpoint = transfer->endpoint;
2485 urb->buffer = transfer->buffer;
2486 urb->buffer_length = transfer->length;
2488 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2489 if (UNLIKELY(r < 0)) {
2492 if (errno == ENODEV)
2493 return LIBUSB_ERROR_NO_DEVICE;
2495 usbi_err(TRANSFER_CTX(transfer),
2496 "submiturb failed error %d errno=%d", r, errno);
2497 return LIBUSB_ERROR_IO;
2499 return LIBUSB_SUCCESS;
2502 static int op_submit_transfer(struct usbi_transfer *itransfer) {
2503 struct libusb_transfer *transfer
2504 = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2506 switch (transfer->type) {
2507 case LIBUSB_TRANSFER_TYPE_CONTROL:
2508 return submit_control_transfer(itransfer);
2509 case LIBUSB_TRANSFER_TYPE_BULK:
2510 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2511 return submit_bulk_transfer(itransfer);
2512 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2513 return submit_bulk_transfer(itransfer);
2514 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2515 return submit_iso_transfer(itransfer);
2517 usbi_err(TRANSFER_CTX(transfer),
2518 "unknown endpoint type %d", transfer->type);
2519 return LIBUSB_ERROR_INVALID_PARAM;
2523 static int op_cancel_transfer(struct usbi_transfer *itransfer) {
2525 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2526 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2528 switch (transfer->type) {
2529 case LIBUSB_TRANSFER_TYPE_BULK:
2530 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2531 if (tpriv->reap_action == ERROR)
2533 /* else, fall through */
2534 case LIBUSB_TRANSFER_TYPE_CONTROL:
2535 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2536 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2537 tpriv->reap_action = CANCELLED;
2540 usbi_err(TRANSFER_CTX(transfer),
2541 "unknown endpoint type %d", transfer->type);
2542 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
2545 if (UNLIKELY(!tpriv->urbs))
2546 RETURN(LIBUSB_ERROR_NOT_FOUND, int);
2548 RETURN(discard_urbs(itransfer, 0, tpriv->num_urbs), int);
2551 static void op_clear_transfer_priv(struct usbi_transfer *itransfer) {
2552 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2553 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2555 /* urbs can be freed also in submit_transfer so lock mutex first */
2556 switch (transfer->type) {
2557 case LIBUSB_TRANSFER_TYPE_CONTROL:
2558 case LIBUSB_TRANSFER_TYPE_BULK:
2559 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2560 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2561 usbi_mutex_lock(&itransfer->lock);
2565 usbi_mutex_unlock(&itransfer->lock);
2567 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2568 usbi_mutex_lock(&itransfer->lock);
2569 if (tpriv->iso_urbs)
2570 free_iso_urbs(tpriv);
2571 usbi_mutex_unlock(&itransfer->lock);
2574 usbi_err(TRANSFER_CTX(transfer),
2575 "unknown endpoint type %d", transfer->type);
2579 static int handle_bulk_completion(struct libusb_device_handle *handle, // XXX added saki
2580 struct usbi_transfer *itransfer,
2581 struct usbfs_urb *urb) {
2582 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2583 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2584 int urb_idx = urb - tpriv->urbs;
2586 usbi_mutex_lock(&itransfer->lock);
2587 usbi_dbg("handling completion status %d of bulk urb %d/%d",
2588 urb->status, urb_idx + 1, tpriv->num_urbs);
2590 tpriv->num_retired++;
2592 if (UNLIKELY(tpriv->reap_action != NORMAL)) {
2593 /* cancelled, submit_fail, or completed early */
2594 usbi_dbg("abnormal reap: urb status %d", urb->status);
2596 /* even though we're in the process of cancelling, it's possible that
2597 * we may receive some data in these URBs that we don't want to lose.
2599 * 1. while the kernel is cancelling all the packets that make up an
2600 * URB, a few of them might complete. so we get back a successful
2601 * cancellation *and* some data.
2602 * 2. we receive a short URB which marks the early completion condition,
2603 * so we start cancelling the remaining URBs. however, we're too
2604 * slow and another URB completes (or at least completes partially).
2605 * (this can't happen since we always use BULK_CONTINUATION.)
2607 * When this happens, our objectives are not to lose any "surplus" data,
2608 * and also to stick it at the end of the previously-received data
2609 * (closing any holes), so that libusb reports the total amount of
2610 * transferred data and presents it in a contiguous chunk.
2612 if (urb->actual_length > 0) {
2613 unsigned char *target = transfer->buffer + itransfer->transferred;
2614 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2615 if (urb->buffer != target) {
2616 usbi_dbg("moving surplus data from offset %d to offset %d",
2617 (unsigned char *) urb->buffer - transfer->buffer,
2618 target - transfer->buffer);
2619 memmove(target, urb->buffer, urb->actual_length);
2621 itransfer->transferred += urb->actual_length;
2624 if (tpriv->num_retired == tpriv->num_urbs) {
2625 usbi_dbg("abnormal reap: last URB handled, reporting");
2626 if (tpriv->reap_action != COMPLETED_EARLY
2627 && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2628 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2634 itransfer->transferred += urb->actual_length;
2636 /* Many of these errors can occur on *any* urb of a multi-urb
2637 * transfer. When they do, we tear down the rest of the transfer.
2639 switch (urb->status) {
2642 case -EREMOTEIO: /* short transfer */
2644 case -ENOENT: /* cancelled */
2649 usbi_dbg("device removed");
2650 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2651 goto cancel_remaining;
2653 usbi_dbg("detected endpoint stall");
2654 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2655 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2656 LOGE("LIBUSB_TRANSFER_STALL");
2657 op_clear_halt(handle, urb->endpoint); // XXX added saki
2658 goto cancel_remaining;
2660 /* overflow can only ever occur in the last urb */
2661 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2662 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2663 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2670 usbi_dbg("low level error %d", urb->status);
2671 tpriv->reap_action = ERROR;
2672 goto cancel_remaining;
2674 usbi_warn(ITRANSFER_CTX(itransfer),
2675 "unrecognised urb status %d", urb->status);
2676 tpriv->reap_action = ERROR;
2677 goto cancel_remaining;
2680 /* if we're the last urb or we got less data than requested then we're done */
2681 if (urb_idx == tpriv->num_urbs - 1) {
2682 usbi_dbg("last URB in transfer --> complete!");
2684 } else if (urb->actual_length < urb->buffer_length) {
2685 usbi_dbg("short transfer %d/%d --> complete!",
2686 urb->actual_length, urb->buffer_length);
2687 if (tpriv->reap_action == NORMAL)
2688 tpriv->reap_action = COMPLETED_EARLY;
2693 if (ERROR == tpriv->reap_action
2694 && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2695 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2697 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2700 /* cancel remaining urbs and wait for their completion before reporting results */
2701 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2704 usbi_mutex_unlock(&itransfer->lock);
2705 return LIBUSB_SUCCESS;
2711 usbi_mutex_unlock(&itransfer->lock);
2712 return CANCELLED == tpriv->reap_action ?
2713 usbi_handle_transfer_cancellation(itransfer) :
2714 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2717 static int handle_iso_completion(struct libusb_device_handle *handle, // XXX added saki
2718 struct usbi_transfer *itransfer,
2719 struct usbfs_urb *urb) {
2720 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2721 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2722 int num_urbs = tpriv->num_urbs;
2725 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2727 usbi_mutex_lock(&itransfer->lock);
2728 for (i = 0; i < num_urbs; i++) {
2729 if (urb == tpriv->iso_urbs[i]) {
2734 if (UNLIKELY(urb_idx == 0)) {
2735 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!"); // crash 2014/09/29 SIGSEGV/SEGV_MAPERR
2736 usbi_mutex_unlock(&itransfer->lock);
2737 return LIBUSB_ERROR_NOT_FOUND;
2740 usbi_dbg("handling completion status %d of iso urb %d/%d",
2741 urb->status, urb_idx, num_urbs);
2743 /* copy isochronous results back in */
2745 for (i = 0; i < urb->number_of_packets; i++) {
2746 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2747 struct libusb_iso_packet_descriptor *lib_desc =
2748 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2749 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2750 switch (urb_desc->status) {
2753 case -ENOENT: /* cancelled */
2758 usbi_dbg("device removed");
2759 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2762 usbi_dbg("detected endpoint stall");
2763 lib_desc->status = LIBUSB_TRANSFER_STALL;
2764 LOGE("LIBUSB_TRANSFER_STALL");
2765 op_clear_halt(handle, urb->endpoint); // XXX added saki
2768 usbi_dbg("overflow error");
2769 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2777 usbi_dbg("low-level USB error %d", urb_desc->status);
2778 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2781 usbi_warn(TRANSFER_CTX(transfer),
2782 "unrecognised urb status %d", urb_desc->status);
2783 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2786 lib_desc->actual_length = urb_desc->actual_length;
2789 tpriv->num_retired++;
2791 if (UNLIKELY(tpriv->reap_action != NORMAL)) { /* cancelled or submit_fail */
2792 usbi_dbg("CANCEL: urb status %d", urb->status);
2794 if (tpriv->num_retired == num_urbs) {
2795 usbi_dbg("CANCEL: last URB handled, reporting");
2796 free_iso_urbs(tpriv);
2797 if (tpriv->reap_action == CANCELLED) {
2798 usbi_mutex_unlock(&itransfer->lock);
2799 return usbi_handle_transfer_cancellation(itransfer);
2801 usbi_mutex_unlock(&itransfer->lock);
2802 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2808 switch (urb->status) {
2811 case -ENOENT: /* cancelled */
2815 usbi_dbg("device removed");
2816 status = LIBUSB_TRANSFER_NO_DEVICE;
2819 usbi_warn(TRANSFER_CTX(transfer),
2820 "unrecognised urb status %d", urb->status);
2821 status = LIBUSB_TRANSFER_ERROR;
2825 /* if we're the last urb then we're done */
2826 if (urb_idx == num_urbs) {
2827 usbi_dbg("last URB in transfer --> complete!");
2828 free_iso_urbs(tpriv);
2829 usbi_mutex_unlock(&itransfer->lock);
2830 return usbi_handle_transfer_completion(itransfer, status);
2834 usbi_mutex_unlock(&itransfer->lock);
2835 return LIBUSB_SUCCESS;
2838 static int handle_control_completion(struct libusb_device_handle *handle, // XXX added saki
2839 struct usbi_transfer *itransfer,
2840 struct usbfs_urb *urb) {
2841 struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2844 usbi_mutex_lock(&itransfer->lock);
2845 usbi_dbg("handling completion status %d", urb->status);
2847 itransfer->transferred += urb->actual_length;
2849 if (UNLIKELY(tpriv->reap_action == CANCELLED)) {
2850 if (urb->status != 0 && urb->status != -ENOENT)
2851 usbi_warn(ITRANSFER_CTX(itransfer),
2852 "cancel: unrecognised urb status %d", urb->status);
2857 usbi_mutex_unlock(&itransfer->lock);
2858 return usbi_handle_transfer_cancellation(itransfer);
2861 switch (urb->status) {
2863 status = LIBUSB_TRANSFER_COMPLETED;
2865 case -ENOENT: /* cancelled */
2866 status = LIBUSB_TRANSFER_CANCELLED;
2870 usbi_dbg("device removed");
2871 status = LIBUSB_TRANSFER_NO_DEVICE;
2874 usbi_dbg("unsupported control request");
2875 status = LIBUSB_TRANSFER_STALL;
2876 LOGE("LIBUSB_TRANSFER_STALL");
2877 op_clear_halt(handle, urb->endpoint); // XXX added saki
2880 usbi_dbg("control overflow error");
2881 status = LIBUSB_TRANSFER_OVERFLOW;
2888 usbi_dbg("low-level bus error occurred");
2889 status = LIBUSB_TRANSFER_ERROR;
2892 usbi_warn(ITRANSFER_CTX(itransfer),
2893 "unrecognised urb status %d", urb->status);
2894 status = LIBUSB_TRANSFER_ERROR;
2899 free(tpriv->urbs); // crash
2902 usbi_mutex_unlock(&itransfer->lock);
2903 return usbi_handle_transfer_completion(itransfer, status);
2906 static int reap_for_handle(struct libusb_device_handle *handle) {
2907 struct android_device_handle_priv *hpriv = _device_handle_priv(handle);
2909 struct usbfs_urb *urb;
2910 struct usbi_transfer *itransfer;
2911 struct libusb_transfer *transfer;
2913 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2914 if (r == -1 && errno == EAGAIN)
2916 if (UNLIKELY(r < 0)) {
2917 if (errno == ENODEV)
2918 return LIBUSB_ERROR_NO_DEVICE;
2920 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d", r, errno);
2921 return LIBUSB_ERROR_IO;
2924 itransfer = urb->usercontext;
2925 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2927 usbi_dbg("urb type=%d status=%d transferred=%d",
2928 urb->type, urb->status, urb->actual_length);
2930 switch (transfer->type) {
2931 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2932 return handle_iso_completion(handle, itransfer, urb);
2933 case LIBUSB_TRANSFER_TYPE_BULK:
2934 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2935 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2936 return handle_bulk_completion(handle, itransfer, urb);
2937 case LIBUSB_TRANSFER_TYPE_CONTROL:
2938 return handle_control_completion(handle, itransfer, urb);
2940 usbi_err(HANDLE_CTX(handle),
2941 "unrecognised endpoint type %x", transfer->type);
2942 return LIBUSB_ERROR_OTHER;
2946 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds,
2947 POLL_NFDS_TYPE nfds, int num_ready) {
2951 usbi_mutex_lock(&ctx->open_devs_lock);
2952 for (i = 0; i < nfds && num_ready > 0; i++) {
2953 struct pollfd *pollfd = &fds[i];
2954 struct libusb_device_handle *handle;
2955 struct android_device_handle_priv *hpriv = NULL;
2957 if (!pollfd->revents)
2961 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle)
2963 hpriv = _device_handle_priv(handle);
2964 if (hpriv->fd == pollfd->fd)
2968 if (!hpriv || hpriv->fd != pollfd->fd) {
2969 usbi_err(ctx, "cannot find handle for fd %d\n",
2974 if (pollfd->revents & POLLERR) {
2975 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2976 usbi_mutex_lock(&ctx->events_lock); // XXX as a note of usbi_handle_disconnect shows that need event_lock locked
2977 usbi_handle_disconnect(handle);
2978 usbi_mutex_unlock(&ctx->events_lock); // XXX
2979 /* device will still be marked as attached if hotplug monitor thread
2980 * hasn't processed remove event yet */
2981 usbi_mutex_static_lock(&android_hotplug_lock);
2982 if (handle->dev->attached)
2983 android_device_disconnected(handle->dev->bus_number,
2984 handle->dev->device_address, NULL);
2985 usbi_mutex_static_unlock(&android_hotplug_lock);
2990 r = reap_for_handle(handle);
2992 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
3000 usbi_mutex_unlock(&ctx->open_devs_lock);
3004 static int op_clock_gettime(int clk_id, struct timespec *tp) {
3006 case USBI_CLOCK_MONOTONIC:
3007 return clock_gettime(monotonic_clkid, tp);
3008 case USBI_CLOCK_REALTIME:
3009 return clock_gettime(CLOCK_REALTIME, tp);
3011 return LIBUSB_ERROR_INVALID_PARAM;
3015 #ifdef USBI_TIMERFD_AVAILABLE
3016 static clockid_t op_get_timerfd_clockid(void)
3018 return monotonic_clkid;
3023 const struct usbi_os_backend android_usbfs_backend = {
3024 .name = "Android usbfs",
3025 .caps = USBI_CAP_HAS_HID_ACCESS | USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
3027 .init2 = op_init2, // XXX
3029 .get_device_list = NULL,
3030 .hotplug_poll = op_hotplug_poll,
3031 .get_raw_descriptor = op_get_raw_descriptor, // XXX
3032 .get_device_descriptor = op_get_device_descriptor,
3033 .get_active_config_descriptor = op_get_active_config_descriptor,
3034 .get_config_descriptor = op_get_config_descriptor,
3035 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
3036 .set_device_fd = op_set_device_fd, // XXX add for no-rooted Android devices
3039 .get_configuration = op_get_configuration,
3040 .set_configuration = op_set_configuration,
3041 .claim_interface = op_claim_interface,
3042 .release_interface = op_release_interface,
3044 .set_interface_altsetting = op_set_interface,
3045 .clear_halt = op_clear_halt,
3046 .reset_device = op_reset_device,
3048 .alloc_streams = op_alloc_streams,
3049 .free_streams = op_free_streams,
3051 .kernel_driver_active = op_kernel_driver_active,
3052 .detach_kernel_driver = op_detach_kernel_driver,
3053 .attach_kernel_driver = op_attach_kernel_driver,
3055 .destroy_device = op_destroy_device,
3057 .submit_transfer = op_submit_transfer,
3058 .cancel_transfer = op_cancel_transfer,
3059 .clear_transfer_priv = op_clear_transfer_priv,
3061 .handle_events = op_handle_events,
3063 .clock_gettime = op_clock_gettime,
3065 #ifdef USBI_TIMERFD_AVAILABLE
3066 .get_timerfd_clockid = op_get_timerfd_clockid,
3069 .device_priv_size = sizeof(struct android_device_priv),
3070 .device_handle_priv_size = sizeof(struct android_device_handle_priv),
3071 .transfer_priv_size = sizeof(struct android_transfer_priv),
3072 .add_iso_packet_size = 0,