Merge tag 'v0.2.0'
[rtmpclient.git] / app / src / main / jni / libusb / libusb / os / android_usbfs.c
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  *********************************************************************/
6 /*
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>
12  *
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.
17  *
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.
22  *
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
26  */
27
28 #define LOCAL_DEBUG 0
29
30 #define LOG_TAG "libusb/usbfs"
31 #if 1   // デバッグ情報を出さない時1
32         #ifndef LOG_NDEBUG
33                 #define LOG_NDEBUG              // LOGV/LOGD/MARKを出力しない時
34                 #endif
35         #undef USE_LOGALL                       // 指定したLOGxだけを出力
36 #else
37         #define USE_LOGALL
38         #undef LOG_NDEBUG
39         #undef NDEBUG
40         #define GET_RAW_DESCRIPTOR
41 #endif
42
43 #include "config.h"
44 #include <assert.h>
45 #include <ctype.h>
46 #include <dirent.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <poll.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <sys/ioctl.h>
54 #include <sys/stat.h>
55 #include <sys/types.h>
56 #include <sys/utsname.h>
57 #include <unistd.h>
58
59 #include "libusb.h"
60 #include "libusbi.h"
61 #include "android_usbfs.h"
62
63 /* sysfs vs usbfs:
64  * opening a usbfs node causes the device to be resumed, so we attempt to
65  * avoid this during enumeration.
66  *
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
78  *
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.
83  *
84  * If we also have all descriptors, we can obtain the device descriptor and
85  * configuration without touching usbfs at all.
86  */
87
88 /* endianness for multi-byte fields:
89  *
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.
93  *
94  * In sysfs all descriptors are bus-endian.
95  */
96
97 static const char *usbfs_path = NULL;
98
99 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
100 static int usbdev_names = 0;
101
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.
107  *
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
115  * reject such URBs).
116  */
117 static int supports_flag_bulk_continuation = -1;
118
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.
122  */
123 static int supports_flag_zero_packet = -1;
124
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;
128
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;
133
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;
138
139 /* how many times have we initted (and not exited) ? */
140 static int init_count = 0;
141
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;
146
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);
152
153 #if !defined(USE_UDEV)
154 static int android_default_scan_devices(struct libusb_context *ctx);
155 #endif
156
157 struct android_device_priv {
158         char *sysfs_dir;
159         unsigned char *descriptors;
160         int descriptors_len;
161         int active_config; /* cache val for !sysfs_can_relate_devices  */
162         int fd;
163 };
164
165 struct android_device_handle_priv {
166         int fd;
167         uint32_t caps;
168 };
169
170 enum reap_action {
171         NORMAL = 0,
172         /* submission failed after the first URB, so await cancellation/completion
173          * of all the others */
174         SUBMIT_FAILED,
175
176         /* cancelled by user or timeout */
177         CANCELLED,
178
179         /* completed multi-URB transfer in non-final URB */
180         COMPLETED_EARLY,
181
182         /* one or more urbs encountered a low-level error */
183         ERROR,
184 };
185
186 struct android_transfer_priv {
187         union {
188                 struct usbfs_urb *urbs;
189                 struct usbfs_urb **iso_urbs;
190         };
191
192         enum reap_action reap_action;
193         int num_urbs;
194         int num_retired;
195         enum libusb_transfer_status reap_status;
196
197         /* next iso packet in user-supplied transfer to be populated */
198         int iso_packet_offset;
199 };
200
201 #if LOCAL_DEBUG
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);
207         }
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);
215 }
216 #endif
217
218 /**
219  * this is original _get_usbfs_fd (name changed to __get_usbfs_fd)
220  */
221 static int __get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent) {
222
223         struct libusb_context *ctx = DEVICE_CTX(dev);
224         char path[PATH_MAX];
225         int fd;
226         int delay = 10000;
227
228         if (usbdev_names)
229                 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
230                         usbfs_path, dev->bus_number, dev->device_address);
231         else
232                 snprintf(path, PATH_MAX, "%s/%03d/%03d",
233                         usbfs_path, dev->bus_number, dev->device_address);
234
235         fd = open(path, mode);
236         if (LIKELY(fd != -1))
237                 return fd; /* Success */
238
239         if (errno == ENOENT) {
240                 if (!silent)
241                         usbi_err(ctx, "File doesn't exist, wait %d ms and try again\n", delay / 1000);
242
243                 /* Wait 10ms for USB device path creation.*/
244                 usleep(delay);
245
246                 fd = open(path, mode);
247                 if (LIKELY(fd != -1))
248                         return fd; /* Success */
249         }
250
251         if (!silent) {
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 "
256                                         "device nodes.");
257         }
258
259         if (errno == EACCES)
260                 return LIBUSB_ERROR_ACCESS;
261         if (errno == ENOENT)
262                 return LIBUSB_ERROR_NO_DEVICE;
263         return LIBUSB_ERROR_IO;
264 }
265
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) {
268 #ifdef __ANDROID__
269         struct android_device_priv *dpriv = _device_priv(device);
270
271         if (LIKELY(dpriv->fd > 0))
272                 return dpriv->fd;
273         else {
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);
278 #else
279                 usbi_dbg("fd have not set yet. device=%x,fd=%d", (long )device, dpriv->fd);
280 #endif
281                 return __get_usbfs_fd(device, mode, silent);
282         }
283 #else
284         return __get_usbfs_fd(device, mode, silent);
285 #endif
286 }
287
288 static struct android_device_priv *_device_priv(struct libusb_device *dev) {
289         return (struct android_device_priv *) dev->os_priv;
290 }
291
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;
295 }
296
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) {
300         int busnum, devnum;
301
302         if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
303                 return LIBUSB_SUCCESS;
304
305         usbi_dbg("found: %s", entry->d_name);
306         if (bus_p != NULL)
307                 *bus_p = busnum;
308         if (dev_p != NULL)
309                 *dev_p = devnum;
310         return 1;
311 }
312
313 static int check_usb_vfs(const char *dirname) {
314         DIR *dir;
315         struct dirent *entry;
316         int found = 0;
317
318         dir = opendir(dirname);
319         if (!dir)
320                 return LIBUSB_SUCCESS;
321
322         while ((entry = readdir(dir)) != NULL ) {
323                 if (entry->d_name[0] == '.')
324                         continue;
325
326                 /* We assume if we find any files that it must be the right place */
327                 found = 1;
328                 break;
329         }
330
331         closedir(dir);
332         return found;
333 }
334
335 static const char *find_usbfs_path(void) {
336         const char *path = "/dev/bus/usb";
337         const char *ret = NULL;
338
339         if (check_usb_vfs(path)) {
340                 ret = path;
341         } else {
342                 path = "/proc/bus/usb";
343                 if (check_usb_vfs(path))
344                         ret = path;
345         }
346
347         /* look for /dev/usbdev*.* if the normal places fail */
348         if (ret == NULL) {
349                 struct dirent *entry;
350                 DIR *dir;
351
352                 path = "/dev";
353                 dir = opendir(path);
354                 if (dir != NULL) {
355                         while ((entry = readdir(dir)) != NULL ) {
356                                 if (_is_usbdev_entry(entry, NULL, NULL)) {
357                                         /* found one; that's enough */
358                                         ret = path;
359                                         usbdev_names = 1;
360                                         break;
361                                 }
362                         }
363                         closedir(dir);
364                 }
365         }
366
367         if (ret != NULL)
368                 usbi_dbg("found usbfs at %s", ret);
369
370         return ret;
371 }
372
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
377         struct timespec ts;
378         int r;
379
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);
383         if (r == 0)
384                 return CLOCK_MONOTONIC;
385         usbi_dbg("monotonic clock doesn't work, errno %d", errno);
386 #endif
387
388         return CLOCK_REALTIME;
389 }
390
391 static int kernel_version_ge(int major, int minor, int sublevel) {
392         struct utsname uts;
393         int atoms, kmajor, kminor, ksublevel;
394
395         if (uname(&uts) < 0)
396                 return -1;
397         atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
398         if (UNLIKELY(atoms < 1))
399                 return -1;
400
401         if (kmajor > major)
402                 return 1;
403         if (kmajor < major)
404                 return 0;
405
406         /* kmajor == major */
407         if (atoms < 2)
408                 return 0 == minor && 0 == sublevel;
409         if (kminor > minor)
410                 return 1;
411         if (kminor < minor)
412                 return 0;
413
414         /* kminor == minor */
415         if (atoms < 3)
416                 return 0 == sublevel;
417
418         return ksublevel >= sublevel;
419 }
420
421 static int op_init2(struct libusb_context *ctx, const char *usbfs) {    // XXX
422         struct stat statbuf;
423         int r;
424
425         ENTER();
426         if (!usbfs || !strlen(usbfs)) {
427                 usbfs_path = find_usbfs_path();
428         } else {
429                 usbfs_path = usbfs;
430         }
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);
435         }
436
437         if (monotonic_clkid == -1)
438                 monotonic_clkid = find_monotonic_clock();
439
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);
447                 }
448         }
449
450         if (supports_flag_bulk_continuation)
451                 usbi_dbg("bulk continuation flag supported");
452
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);
460                 }
461         }
462
463         if (supports_flag_zero_packet)
464                 usbi_dbg("zero length packet flag supported");
465
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);
473                 }
474         }
475
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);
483                 }
484         }
485
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;
492                 }
493         }
494
495         if (sysfs_can_relate_devices)
496                 usbi_dbg("sysfs can relate devices");
497
498         if (sysfs_has_descriptors)
499                 usbi_dbg("sysfs has complete descriptors");
500
501         usbi_mutex_static_lock(&android_hotplug_startstop_lock);
502         r = LIBUSB_SUCCESS;
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");
509                 }
510         }
511         if (r == LIBUSB_SUCCESS) {
512                 LOGI("call android_scan_devices");
513                 r = android_scan_devices(ctx);
514                 if (r == LIBUSB_SUCCESS)
515                         init_count++;
516                 else if (init_count == 0)
517                         android_stop_event_monitor();
518         } else {
519                 LOGE("error starting hotplug event monitor");
520                 usbi_err(ctx, "error starting hotplug event monitor");
521         }
522         usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
523
524         RETURN(r, int);
525 }
526
527 static int op_init(struct libusb_context *ctx) {
528         return op_init2(ctx, NULL);
529 #if 0
530         struct stat statbuf;
531         int r;
532
533         usbfs_path = find_usbfs_path();
534         if (UNLIKELY(!usbfs_path)) {
535                 usbi_err(ctx, "could not find usbfs");
536                 return LIBUSB_ERROR_OTHER;
537         }
538
539         if (monotonic_clkid == -1)
540                 monotonic_clkid = find_monotonic_clock();
541
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;
548                 }
549         }
550
551         if (supports_flag_bulk_continuation)
552                 usbi_dbg("bulk continuation flag supported");
553
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;
560                 }
561         }
562
563         if (supports_flag_zero_packet)
564                 usbi_dbg("zero length packet flag supported");
565
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;
572                 }
573         }
574
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;
581                 }
582         }
583
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;
590                 }
591         }
592
593         if (sysfs_can_relate_devices)
594                 usbi_dbg("sysfs can relate devices");
595
596         if (sysfs_has_descriptors)
597                 usbi_dbg("sysfs has complete descriptors");
598
599         usbi_mutex_static_lock(&android_hotplug_startstop_lock);
600         r = LIBUSB_SUCCESS;
601         if (init_count == 0) {
602                 LOGI("start up hotplug event handler");
603                 r = android_start_event_monitor();
604         }
605         if (r == LIBUSB_SUCCESS) {
606                 r = android_scan_devices(ctx);
607                 if (r == LIBUSB_SUCCESS)
608                         init_count++;
609                 else if (init_count == 0)
610                         android_stop_event_monitor();
611         } else
612                 usbi_err(ctx, "error starting hotplug event monitor");
613         usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
614
615         return r;
616 #endif
617 }
618
619
620 static void op_exit(void) {
621         ENTER();
622
623         usbi_mutex_static_lock(&android_hotplug_startstop_lock);
624         assert(init_count != 0);
625         if (!--init_count) {
626                 /* tear down event handler */
627                 (void) android_stop_event_monitor();
628         }
629         usbi_mutex_static_unlock(&android_hotplug_startstop_lock);
630
631         EXIT();
632 }
633
634 static int android_start_event_monitor(void) {
635         ENTER();
636 #ifdef __ANDROID__
637         // do nothing
638         RETURN(LIBUSB_SUCCESS, int);
639 #else
640 #if defined(USE_UDEV)
641         RETURN(android_udev_start_event_monitor(), int);
642 #else
643         RETURN(android_netlink_start_event_monitor(), int);
644 #endif
645 #endif
646 }
647
648 static int android_stop_event_monitor(void) {
649         ENTER();
650 #ifdef __ANDROID__
651         RETURN(LIBUSB_SUCCESS, int);
652 #else
653 #if defined(USE_UDEV)
654         RETURN(android_udev_stop_event_monitor(), int);
655 #else
656         RETURN(android_netlink_stop_event_monitor(), int);
657 #endif
658 #endif
659 }
660
661 static int android_scan_devices(struct libusb_context *ctx) {
662         ENTER();
663         int ret = LIBUSB_SUCCESS;
664
665 #ifdef __ANDROID__
666         // do nothing
667 #else
668         usbi_mutex_static_lock(&android_hotplug_lock);
669
670 #if defined(USE_UDEV)
671         ret = android_udev_scan_devices(ctx);
672 #else
673         ret = android_default_scan_devices(ctx);
674 #endif
675
676         usbi_mutex_static_unlock(&android_hotplug_lock);
677 #endif
678         RETURN(ret, int);
679 }
680
681 static void op_hotplug_poll(void) {
682         ENTER();
683 #ifdef __ANDROID__
684         // do nothing
685 #else
686 #if defined(USE_UDEV)
687         android_udev_hotplug_poll();
688 #else
689         android_netlink_hotplug_poll();
690 #endif
691 #endif
692         EXIT();
693 }
694
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];
698         int fd;
699
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;
707         }
708
709         return fd;
710 }
711
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,
714                 const char *attr) {
715         char filename[PATH_MAX];
716         FILE *f;
717         int r, value;
718
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;
726                 }
727                 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
728                 return LIBUSB_ERROR_IO;
729         }
730
731         r = fscanf(f, "%d", &value);
732         fclose(f);
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) */
736         }
737         if (UNLIKELY(value < 0)) {
738                 usbi_err(ctx, "%s contains a negative value", filename);
739                 return LIBUSB_ERROR_IO;
740         }
741
742         return value;
743 }
744
745 // XXX
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);
749
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);
755         }
756         *descriptors_len = priv->descriptors_len;
757         return LIBUSB_SUCCESS;
758 }
759
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);
763
764         if (!host_endian)
765                 return LIBUSB_ERROR_INVALID_PARAM;
766         *host_endian = sysfs_has_descriptors ? 0 : 1;
767         memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
768
769         return LIBUSB_SUCCESS;
770 }
771
772 /* read the bConfigurationValue for a device */
773 static int sysfs_get_active_config(struct libusb_device *dev, int *config) {
774         char *endptr;
775         char tmp[5] = { 0, 0, 0, 0, 0 };
776         long num;
777         int fd;
778         ssize_t r;
779
780         fd = _open_sysfs_attr(dev, "bConfigurationValue");
781         if (UNLIKELY(fd < 0))
782                 return fd;
783
784         r = read(fd, tmp, sizeof(tmp));
785         close(fd);
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;
790         } else if (r == 0) {
791                 usbi_dbg("device unconfigured");
792                 *config = -1;
793                 return LIBUSB_SUCCESS;
794         }
795
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;
802         }
803
804         num = strtol(tmp, &endptr, 10);
805         if (endptr == tmp) {
806                 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
807                 return LIBUSB_ERROR_IO;
808         }
809
810         *config = (int) num;
811         return LIBUSB_SUCCESS;
812 }
813
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) {
817         int sysfs_attr;
818
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;
825                 }
826
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);
832                 }
833
834                 return LIBUSB_SUCCESS;
835         }
836
837         usbi_dbg("scan %s", sys_name);
838
839         sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
840         if (0 > sysfs_attr)
841                 return sysfs_attr;
842         if (sysfs_attr > 255)
843                 return LIBUSB_ERROR_INVALID_PARAM;
844         *busnum = (uint8_t) sysfs_attr;
845
846         sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
847         if (0 > sysfs_attr)
848                 return sysfs_attr;
849         if (sysfs_attr > 255)
850                 return LIBUSB_ERROR_INVALID_PARAM;
851
852         *devaddr = (uint8_t) sysfs_attr;
853
854         usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
855
856         return LIBUSB_SUCCESS;
857 }
858
859 /*
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
863  */
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;
867         int i;
868
869         for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
870                 if (size == 0)
871                         return LIBUSB_ERROR_NOT_FOUND;
872
873                 if (size < LIBUSB_DT_HEADER_SIZE) {
874                         usbi_err(ctx, "short descriptor read %d/2", size);
875                         return LIBUSB_ERROR_IO;
876                 }
877                 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
878
879                 if (header.bDescriptorType == descriptor_type)  // XXX
880                         return i;
881         }
882         usbi_err(ctx, "bLength overflow by %d bytes", -size);
883         return LIBUSB_ERROR_IO;
884 }
885
886
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;
891         int i;
892
893         for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
894                 if (size == 0)
895                         return LIBUSB_ERROR_NOT_FOUND;
896
897                 if (size < LIBUSB_DT_HEADER_SIZE) {
898                         usbi_err(ctx, "short descriptor read %d/2", size);
899                         return LIBUSB_ERROR_IO;
900                 }
901                 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
902
903                 if (i && header.bDescriptorType == descriptor_type)
904                         return i;
905         }
906         usbi_err(ctx, "bLength overflow by %d bytes", -size);
907         return LIBUSB_ERROR_IO;
908 }
909
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;
915
916         if (size == 0)
917                 return LIBUSB_ERROR_NOT_FOUND;
918
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;
923         }
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;
928         }
929
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;
935         }
936
937         /*
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.
940          *
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.
944          */
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)
948                         next = size;
949                 if (next < 0)
950                         return next;
951
952                 if (next != config.wTotalLength)
953                         usbi_warn(ctx, "config length mismatch wTotalLength "
954                                 "%d real %d", config.wTotalLength, next);
955                 return next;
956         } else {
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);
964                         return size;
965                 } else
966                         return config.wTotalLength;
967         }
968 }
969
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;
977
978         *buffer = NULL;
979         /* Unlike the device desc. config descs. are always in raw format */
980         *host_endian = 0;
981
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);
992         if UNLIKELY(r < 0) {
993                 LOGE("could not find config descriptor:r=%d", r);
994                 return r;
995         }
996         descriptors += r;
997         size -= r;
998         /* Seek till the config is found, or till "EOF" */
999         for (; ;) {
1000                 register int next = seek_to_next_config(ctx, descriptors, size);
1001                 if UNLIKELY(next < 0)
1002                         return next;
1003                 config = (struct libusb_config_descriptor *) descriptors;
1004                 if (config->bConfigurationValue == value) {
1005                         *buffer = descriptors;
1006                         return next;
1007                 }
1008                 size -= next;
1009                 descriptors += next;
1010         }
1011 }
1012
1013 static int op_get_active_config_descriptor(struct libusb_device *dev,
1014                 unsigned char *buffer, size_t len, int *host_endian) {
1015         int r, config;
1016         unsigned char *config_desc;
1017
1018         if (sysfs_can_relate_devices) {
1019                 r = sysfs_get_active_config(dev, &config);
1020                 if (UNLIKELY(r < 0))
1021                         return r;
1022         } else {
1023                 /* Use cached bConfigurationValue */
1024                 struct android_device_priv *priv = _device_priv(dev);
1025                 config = priv->active_config;
1026         }
1027         if (config == -1)
1028                 return LIBUSB_ERROR_NOT_FOUND;
1029
1030         r = op_get_config_descriptor_by_value(dev, config, &config_desc,
1031                         host_endian);
1032         if (UNLIKELY(r < 0))
1033                 return r;
1034
1035         len = MIN(len, r);
1036         memcpy(buffer, config_desc, len);
1037         return len;
1038 }
1039
1040 static int op_get_config_descriptor(struct libusb_device *dev,
1041                 uint8_t config_index, unsigned char *buffer, size_t len,
1042                 int *host_endian) {
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;
1047
1048         /* Unlike the device desc. config descs. are always in raw format */
1049         *host_endian = 0;
1050
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);
1063                 return r;
1064         }
1065         descriptors += r;
1066         size -= 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
1071                         return r;
1072                 if (i == config_index)
1073                         break;
1074                 size -= r;
1075                 descriptors += r;
1076         }
1077
1078         len = MIN(len, r);
1079         memcpy(buffer, descriptors, len);
1080         return len;
1081 }
1082
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;
1086         int r;
1087
1088         struct usbfs_ctrltransfer ctrl = {
1089                 .bmRequestType = LIBUSB_ENDPOINT_IN,
1090                 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
1091                 .wValue = 0,
1092                 .wIndex = 0,
1093                 .wLength = 1,
1094                 .timeout = 1000,
1095                 .data = &active_config
1096         };
1097
1098         r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
1099         if (UNLIKELY(r < 0)) {
1100                 if (errno == ENODEV)
1101                         return LIBUSB_ERROR_NO_DEVICE;
1102
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;
1107         }
1108
1109         return active_config;
1110 }
1111
1112 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
1113                 uint8_t devaddr, const char *sysfs_dir) {
1114
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 */
1118         int fd, speed;
1119         ssize_t r;
1120
1121         dev->bus_number = busnum;
1122         dev->device_address = devaddr;
1123
1124         if (sysfs_dir) {
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);
1129
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");
1133                 if (speed >= 0) {
1134                         switch (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;
1139                         default:
1140                                 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
1141                         }
1142                 }
1143         }
1144
1145         /* cache descriptors in memory */
1146         if (sysfs_has_descriptors) {
1147                 fd = _open_sysfs_attr(dev, "descriptors");
1148         } else {
1149                 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
1150         }
1151         if (fd < 0)
1152                 return fd;
1153
1154         do {
1155                 descriptors_size *= 2;
1156                 priv->descriptors = usbi_reallocf(priv->descriptors, descriptors_size);
1157                 if (UNLIKELY(!priv->descriptors)) {
1158                         close(fd);
1159                         return LIBUSB_ERROR_NO_MEM;
1160                 }
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);
1165                 }
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);
1170                         close(fd);
1171                         return LIBUSB_ERROR_IO;
1172                 }
1173                 priv->descriptors_len += r;
1174         } while (priv->descriptors_len == descriptors_size);
1175
1176         close(fd);
1177
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;
1181         }
1182
1183         if (sysfs_can_relate_devices)
1184                 return LIBUSB_SUCCESS;
1185
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;
1199                 } else
1200                         priv->active_config = -1; /* No config dt */
1201
1202                 return LIBUSB_SUCCESS;
1203         }
1204         // if we could get fd of usbfs with read/write access
1205         r = usbfs_get_active_config(dev, fd);
1206         if (r > 0) {
1207                 priv->active_config = r;
1208                 r = LIBUSB_SUCCESS;
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
1214                  * unconfigured. */
1215                 usbi_dbg("active cfg 0? assuming unconfigured device");
1216                 priv->active_config = -1;
1217                 r = LIBUSB_SUCCESS;
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"
1222                                         " unconfigured");
1223                 priv->active_config = -1;
1224                 r = LIBUSB_SUCCESS;
1225         } /* else r < 0, just return the error code */
1226
1227         close(fd);
1228         return r;
1229 }
1230
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;
1237
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;
1242         }
1243
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);
1248                 *tmp = '\0';
1249         } else {
1250                 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1251                         parent_sysfs_dir);
1252                 free(parent_sysfs_dir);
1253                 return LIBUSB_SUCCESS;
1254         }
1255
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);
1260                 free(tmp);
1261                 if (0 > ret) {
1262                         return LIBUSB_ERROR_NO_MEM;
1263                 }
1264         }
1265
1266 retry:
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)
1270         {
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);
1274                         break;
1275                 }
1276         }
1277         usbi_mutex_unlock(&ctx->usb_devs_lock);
1278
1279         if (!dev->parent_dev && add_parent) {
1280                 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1281                         parent_sysfs_dir);
1282                 sysfs_scan_device(ctx, parent_sysfs_dir);
1283                 add_parent = 0;
1284                 goto retry;
1285         }
1286
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);
1289
1290         free(parent_sysfs_dir);
1291
1292         return LIBUSB_SUCCESS;
1293 }
1294
1295 static int android_initialize_device(struct libusb_device *dev,
1296         uint8_t busnum, uint8_t devaddr, int fd) {
1297
1298         ENTER();
1299
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
1303         int speed;
1304         ssize_t r;
1305
1306         dev->bus_number = busnum;
1307         dev->device_address = devaddr;
1308
1309         LOGD("cache descriptors in memory");
1310
1311         priv->descriptors_len = 0;
1312         priv->fd = 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);
1318                 if (length > 0) {
1319                         priv->fd = fd;
1320                         priv->descriptors = usbi_reallocf(priv->descriptors, length);
1321                         if (UNLIKELY(!priv->descriptors)) {
1322                                 RETURN(LIBUSB_ERROR_NO_MEM, int);
1323                         }
1324                         priv->descriptors_len = length;
1325                         memcpy(priv->descriptors, desc, length);
1326                 }
1327         }
1328
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);
1333         }
1334
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;
1346                 } else
1347                         priv->active_config = -1; /* No config dt */
1348
1349                 RETURN(LIBUSB_SUCCESS, int);
1350         }
1351         // if we could get fd of usbfs with read/write access
1352         r = usbfs_get_active_config(dev, fd);
1353         if (r > 0) {
1354                 priv->active_config = r;
1355                 r = LIBUSB_SUCCESS;
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
1361                  * unconfigured. */
1362                 usbi_dbg("active cfg 0? assuming unconfigured device");
1363                 priv->active_config = -1;
1364                 r = LIBUSB_SUCCESS;
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"
1369                                         " unconfigured");
1370                 priv->active_config = -1;
1371                 r = LIBUSB_SUCCESS;
1372         } /* else r < 0, just return the error code */
1373
1374         RETURN(r, int);
1375 }
1376
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) {
1379
1380         ENTER();
1381
1382         unsigned long session_id;
1383         int r = 0;
1384
1385         *dev = NULL;
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
1388          * a session ID. */
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);
1394         }
1395
1396         r = android_initialize_device(*dev, busnum, devaddr, fd);
1397         if (UNLIKELY(r < 0)) {
1398                 LOGE("initialize_device failed: ret=%d", r);
1399                 goto out;
1400         }
1401         r = usbi_sanitize_device(*dev);
1402         if (UNLIKELY(r < 0)) {
1403                 LOGE("usbi_sanitize_device failed: ret=%d", r);
1404                 goto out;
1405         }
1406
1407 out:
1408         if (UNLIKELY(r < 0)) {
1409                 libusb_unref_device(*dev);      // ここで参照カウンタが0になって破棄される
1410                 *dev = NULL;
1411         } else {
1412                 usbi_connect_device(*dev);
1413         }
1414
1415         RETURN(r, int);
1416 }
1417
1418
1419 int android_enumerate_device(struct libusb_context *ctx, uint8_t busnum,
1420                 uint8_t devaddr, const char *sysfs_dir) {
1421
1422         unsigned long session_id;
1423         struct libusb_device *dev;
1424         int r = 0;
1425
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
1428          * a session ID. */
1429         session_id = busnum << 8 | devaddr;
1430         usbi_dbg("busnum %d devaddr %d session_id %ld",
1431                 busnum, devaddr, session_id);
1432
1433         dev = usbi_get_device_by_session_id(ctx, session_id);
1434         if (dev) {
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;
1439         }
1440
1441         usbi_dbg("allocating new device for %d/%d (session %ld)",
1442                 busnum, devaddr, session_id);
1443         dev = usbi_alloc_device(ctx, session_id);
1444         if (UNLIKELY(!dev))
1445                 return LIBUSB_ERROR_NO_MEM;
1446
1447         r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1448         if (UNLIKELY(r < 0))
1449                 goto out;
1450         r = usbi_sanitize_device(dev);
1451         if (UNLIKELY(r < 0))
1452                 goto out;
1453
1454         r = android_get_parent_info(dev, sysfs_dir);
1455         if (UNLIKELY(r < 0))
1456                 goto out;
1457 out:
1458         if (UNLIKELY(r < 0))
1459                 libusb_unref_device(dev);
1460         else
1461                 usbi_connect_device(dev);
1462
1463         return r;
1464 }
1465
1466 void android_hotplug_enumerate(uint8_t busnum, uint8_t devaddr,
1467                 const char *sys_name) {
1468         struct libusb_context *ctx;
1469
1470         usbi_mutex_static_lock(&active_contexts_lock);
1471         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context)
1472         {
1473                 android_enumerate_device(ctx, busnum, devaddr, sys_name);
1474         }
1475         usbi_mutex_static_unlock(&active_contexts_lock);
1476 }
1477
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;
1483
1484         usbi_mutex_static_lock(&active_contexts_lock);
1485         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context)
1486         {
1487                 dev = usbi_get_device_by_session_id(ctx, session_id);
1488                 if (NULL != dev) {
1489                         usbi_disconnect_device(dev);
1490                         libusb_unref_device(dev);
1491                 } else {
1492                         usbi_dbg("device not found for session %x", session_id);
1493                 }
1494         }
1495         usbi_mutex_static_unlock(&active_contexts_lock);
1496 }
1497
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) {
1501         DIR *dir;
1502         char dirpath[PATH_MAX];
1503         struct dirent *entry;
1504         int r = LIBUSB_ERROR_IO;
1505
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 */
1513                 return r;
1514         }
1515
1516         while ((entry = readdir(dir))) {
1517                 int devaddr;
1518
1519                 if (entry->d_name[0] == '.')
1520                         continue;
1521
1522                 devaddr = atoi(entry->d_name);
1523                 if (devaddr == 0) {
1524                         usbi_dbg("unknown dir entry %s", entry->d_name);
1525                         continue;
1526                 }
1527
1528                 if (android_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1529                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1530                         continue;
1531                 }
1532
1533                 r = 0;
1534         }
1535
1536         closedir(dir);
1537         return r;
1538 }
1539
1540 static int usbfs_get_device_list(struct libusb_context *ctx) {
1541         struct dirent *entry;
1542         DIR *buses = opendir(usbfs_path);
1543         int r = 0;
1544
1545         if (!buses) {
1546                 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1547                 return LIBUSB_ERROR_IO;
1548         }
1549
1550         while ((entry = readdir(buses))) {
1551                 int busnum;
1552
1553                 if (entry->d_name[0] == '.')
1554                         continue;
1555
1556                 if (usbdev_names) {
1557                         int devaddr;
1558                         if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1559                                 continue;
1560
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);
1564                                 continue;
1565                         }
1566                 } else {
1567                         busnum = atoi(entry->d_name);
1568                         if (UNLIKELY(busnum == 0)) {
1569                                 usbi_dbg("unknown dir entry %s", entry->d_name);
1570                                 continue;
1571                         }
1572
1573                         r = usbfs_scan_busdir(ctx, busnum);
1574                         if (UNLIKELY(r < 0))
1575                                 break;
1576                 }
1577         }
1578
1579         closedir(buses);
1580         return r;
1581
1582 }
1583 #endif
1584
1585 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname) {
1586         uint8_t busnum, devaddr;
1587         int ret;
1588
1589         ret = android_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname);
1590         if (UNLIKELY(LIBUSB_SUCCESS != ret)) {
1591                 return ret;
1592         }
1593
1594         return android_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff, devname);
1595 }
1596
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;
1602
1603         if (UNLIKELY(!devices)) {
1604                 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1605                 return r;
1606         }
1607
1608         while ((entry = readdir(devices))) {
1609                 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1610                                 || strchr(entry->d_name, ':'))
1611                         continue;
1612
1613                 if (sysfs_scan_device(ctx, entry->d_name)) {
1614                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1615                         continue;
1616                 }
1617
1618                 r = 0;
1619         }
1620
1621         closedir(devices);
1622         return r;
1623 }
1624
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.
1630          *
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.
1635          */
1636         if (sysfs_can_relate_devices != 0)
1637                 return sysfs_get_device_list(ctx);
1638         else
1639                 return usbfs_get_device_list(ctx);
1640 }
1641 #endif
1642
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);
1648         dpriv->fd = fd;
1649         return LIBUSB_SUCCESS;
1650 }
1651
1652 static int op_open(struct libusb_device_handle *handle) {
1653         struct android_device_handle_priv *hpriv = _device_handle_priv(handle);
1654         int r;
1655
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);
1666                         }
1667                         usbi_mutex_static_unlock(&android_hotplug_lock);
1668                 }
1669                 return hpriv->fd;
1670         }
1671
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");
1676                 else
1677                         usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1678                 hpriv->caps = 0;
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;
1683         }
1684
1685         return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1686 }
1687
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);
1691 #ifndef __ANDROID__
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
1694         close(fd);
1695 #endif
1696 }
1697
1698 static int op_get_configuration(struct libusb_device_handle *handle,
1699                 int *config) {
1700         int r;
1701
1702         if (sysfs_can_relate_devices) {
1703                 r = sysfs_get_active_config(handle->dev, config);
1704         } else {
1705                 r = usbfs_get_active_config(handle->dev,
1706                                 _device_handle_priv(handle)->fd);
1707         }
1708         if (UNLIKELY(r < 0))
1709                 return r;
1710
1711         if (*config == -1) {
1712                 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1713                 *config = 0;
1714         }
1715
1716         return LIBUSB_SUCCESS;
1717 }
1718
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);
1723         if (UNLIKELY(r)) {
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;
1730                 }
1731                 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1732                 return LIBUSB_ERROR_OTHER;
1733         }
1734
1735         /* update our cached active config descriptor */
1736         priv->active_config = config;
1737
1738         return LIBUSB_SUCCESS;
1739 }
1740
1741 static int claim_interface(struct libusb_device_handle *handle, int iface) {
1742
1743         ENTER();
1744
1745         const int fd = _device_handle_priv(handle)->fd;
1746         LOGD("interface=%d, fd=%d", iface, fd);
1747
1748         int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1749         if (UNLIKELY(r)) {
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);
1756         }
1757                 LOGE("claim interface failed, error %d errno %d", r, errno);
1758                 RETURN(LIBUSB_ERROR_OTHER, int);
1759         }
1760
1761         RETURN(LIBUSB_SUCCESS, int);
1762 }
1763
1764 static int release_interface(struct libusb_device_handle *handle, int iface) {
1765
1766         ENTER();
1767
1768         const int fd = _device_handle_priv(handle)->fd;
1769         LOGD("interface=%d, fd=%d", iface, fd);
1770
1771         int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1772         if (UNLIKELY(r)) {
1773                 if (errno == ENODEV) {
1774                         RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1775         }
1776                 LOGE("release interface failed, error %d errno %d", r, errno);
1777                 RETURN(LIBUSB_ERROR_OTHER, int);
1778         }
1779
1780         RETURN(LIBUSB_SUCCESS, int);
1781 }
1782
1783 static int op_set_interface(struct libusb_device_handle *handle, int iface, int altsetting) {
1784
1785         ENTER();
1786
1787         const int fd = _device_handle_priv(handle)->fd;
1788         struct usbfs_setinterface setintf;
1789         int r;
1790
1791         setintf.interface = iface;
1792         setintf.altsetting = altsetting;
1793         r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1794         if (UNLIKELY(r)) {
1795                 if (errno == EINVAL) {
1796                         RETURN(LIBUSB_ERROR_NOT_FOUND, int);
1797                 } else if (errno == ENODEV) {
1798                         RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1799                 }
1800                 usbi_err(HANDLE_CTX(handle),
1801                         "setintf failed error %d errno %d", r, errno);
1802                 RETURN(LIBUSB_ERROR_OTHER, int);
1803         }
1804
1805         RETURN(LIBUSB_SUCCESS, int);
1806 }
1807
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);
1813         if (UNLIKELY(r)) {
1814                 if (errno == ENOENT)
1815                         return LIBUSB_ERROR_NOT_FOUND;
1816                 else if (errno == ENODEV)
1817                         return LIBUSB_ERROR_NO_DEVICE;
1818
1819                 usbi_err(HANDLE_CTX(handle),
1820                         "clear_halt failed error %d errno %d", r, errno);
1821                 return LIBUSB_ERROR_OTHER;
1822         }
1823
1824         return LIBUSB_SUCCESS;
1825 }
1826
1827 static int op_reset_device(struct libusb_device_handle *handle) {
1828         const int fd = _device_handle_priv(handle)->fd;
1829         int i, r, ret = 0;
1830
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);
1839                 }
1840         }
1841
1842         usbi_mutex_lock(&handle->lock);
1843         r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1844         if (UNLIKELY(r)) {
1845                 if (errno == ENODEV) {
1846                         ret = LIBUSB_ERROR_NOT_FOUND;
1847                         goto out;
1848                 }
1849
1850                 usbi_err(HANDLE_CTX(handle),
1851                         "reset failed error %d errno %d", r, errno);
1852                 ret = LIBUSB_ERROR_OTHER;
1853                 goto out;
1854         }
1855
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)) {
1859                         /*
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
1863                          */
1864                         r = detach_kernel_driver_and_claim(handle, i);
1865                         if (UNLIKELY(r)) {
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;
1871                         }
1872                 }
1873         }
1874 out:
1875         usbi_mutex_unlock(&handle->lock);
1876         return ret;
1877 }
1878
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;
1882         int r;
1883         struct usbfs_streams *streams;
1884
1885         if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1886                 return LIBUSB_ERROR_INVALID_PARAM;
1887
1888         streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1889         if (!streams)
1890                 return LIBUSB_ERROR_NO_MEM;
1891
1892         streams->num_streams = num_streams;
1893         streams->num_eps = num_endpoints;
1894         memcpy(streams->eps, endpoints, num_endpoints);
1895
1896         r = ioctl(fd, req, streams);
1897
1898         free(streams);
1899
1900         if (r < 0) {
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;
1907
1908                 usbi_err(HANDLE_CTX(handle),
1909                         "streams-ioctl failed error %d errno %d", r, errno);
1910                 return LIBUSB_ERROR_OTHER;
1911         }
1912         return r;
1913 }
1914
1915 static int op_alloc_streams(struct libusb_device_handle *handle,
1916         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1917 {
1918         return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1919                                 num_streams, endpoints, num_endpoints);
1920 }
1921
1922 static int op_free_streams(struct libusb_device_handle *handle,
1923                 unsigned char *endpoints, int num_endpoints)
1924 {
1925         return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1926                                 endpoints, num_endpoints);
1927 }
1928
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;
1932         int r;
1933
1934         getdrv.interface = interface;
1935         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1936         if (UNLIKELY(r)) {
1937                 if (errno == ENODATA)
1938                         return LIBUSB_SUCCESS;
1939                 else if (errno == ENODEV)
1940                         return LIBUSB_ERROR_NO_DEVICE;
1941
1942                 usbi_err(HANDLE_CTX(handle),
1943                         "get driver failed error %d errno %d", r, errno);
1944                 return LIBUSB_ERROR_OTHER;
1945         }
1946
1947         return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1948 }
1949
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;
1954         int r;
1955
1956         command.ifno = interface;
1957         command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1958         command.data = NULL;
1959
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;
1964
1965         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1966         if (UNLIKELY(r)) {
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;
1973
1974                 usbi_err(HANDLE_CTX(handle),
1975                         "detach failed error %d errno %d", r, errno);
1976                 return LIBUSB_ERROR_OTHER;
1977         }
1978
1979         return LIBUSB_SUCCESS;
1980 }
1981
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;
1985         int r;
1986
1987         command.ifno = interface;
1988         command.ioctl_code = IOCTL_USBFS_CONNECT;
1989         command.data = NULL;
1990
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;
2001
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;
2007         }
2008
2009         return LIBUSB_SUCCESS;
2010 }
2011
2012 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle, int interface) {
2013
2014         ENTER();
2015
2016         const int fd = _device_handle_priv(handle)->fd;
2017         struct usbfs_disconnect_claim dc;
2018         int r;
2019
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)) {
2025                 if (r == 0) {
2026                         RETURN(LIBUSB_SUCCESS, int);
2027                 }
2028
2029                 switch (errno) {
2030                 case EBUSY:
2031                         RETURN(LIBUSB_ERROR_BUSY, int);
2032                 case EINVAL:
2033                         RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
2034                 case ENODEV:
2035                         RETURN(LIBUSB_ERROR_NO_DEVICE, int);
2036                 }
2037                 usbi_err(HANDLE_CTX(handle),
2038                         "disconnect-and-claim failed errno %d", errno);
2039                 RETURN(LIBUSB_ERROR_OTHER, int);
2040         }
2041
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) {
2046                 RETURN(r, int);
2047         }
2048
2049         r = claim_interface(handle, interface);
2050         RETURN(r, int);
2051 }
2052
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);
2056         else
2057                 return claim_interface(handle, iface);
2058 }
2059
2060 static int op_release_interface(struct libusb_device_handle *handle, int iface) {
2061         int r;
2062
2063         r = release_interface(handle, iface);
2064         if (UNLIKELY(r))
2065                 return r;
2066
2067         if (handle->auto_detach_kernel_driver)
2068                 op_attach_kernel_driver(handle, iface);
2069
2070         return LIBUSB_SUCCESS;
2071 }
2072
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);
2079 }
2080
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) {
2083         ENTER();
2084
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);
2088         int i, ret = 0;
2089         struct usbfs_urb *urb;
2090
2091         for (i = last_plus_one - 1; i >= first; i--) {
2092                 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
2093                         urb = tpriv->iso_urbs[i];
2094                 else
2095                         urb = &tpriv->urbs[i];
2096
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))
2099                         continue;
2100
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;
2108                 } else {
2109                         usbi_warn(TRANSFER_CTX(transfer),
2110                                 "unrecognised discard errno %d", errno);
2111                         ret = LIBUSB_ERROR_OTHER;
2112                 }
2113         }
2114         RETURN(ret, int);
2115 }
2116
2117 static void free_iso_urbs(struct android_transfer_priv *tpriv) {
2118         int i;
2119         for (i = 0; i < tpriv->num_urbs; i++) {
2120                 struct usbfs_urb *urb = tpriv->iso_urbs[i];
2121                 if (UNLIKELY(!urb))
2122                         break;
2123                 free(urb);
2124         }
2125
2126         free(tpriv->iso_urbs);
2127         tpriv->iso_urbs = NULL;
2128 }
2129
2130 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
2131
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;
2141         int r;
2142         int i;
2143         size_t alloc_size;
2144
2145         if (UNLIKELY(tpriv->urbs))
2146                 return LIBUSB_ERROR_BUSY;
2147
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;
2151
2152         /*
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.
2157          *
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.
2162          *
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.
2166          *
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.
2170          */
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;
2185         } else {
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;
2192         }
2193
2194         int num_urbs = transfer->length / bulk_buffer_len;
2195         int last_urb_partial = 0;
2196
2197         if (transfer->length == 0) {
2198                 num_urbs = 1;
2199         } else if ((transfer->length % bulk_buffer_len) > 0) {
2200                 last_urb_partial = 1;
2201                 num_urbs++;
2202         }
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;
2208         tpriv->urbs = urbs;
2209         tpriv->num_urbs = num_urbs;
2210         tpriv->num_retired = 0;
2211         tpriv->reap_action = NORMAL;
2212         tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2213
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;
2220                         urb->stream_id = 0;
2221                         break;
2222                 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2223                         urb->type = USBFS_URB_TYPE_BULK;
2224                         urb->stream_id = itransfer->stream_id;
2225                         break;
2226                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2227                         urb->type = USBFS_URB_TYPE_INTERRUPT;
2228                         break;
2229                 }
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;
2239                 else
2240                         urb->buffer_length = bulk_buffer_len;
2241
2242                 if (i > 0 && use_bulk_continuation)
2243                         urb->flags |= USBFS_URB_BULK_CONTINUATION;
2244
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;
2249 #if LOCAL_DEBUG
2250                 dump_urb(i, dpriv->fd, urb);
2251 #endif
2252                 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2253                 if (UNLIKELY(r < 0)) {
2254                         if (errno == ENODEV) {
2255                                 r = LIBUSB_ERROR_NO_DEVICE;
2256                         } else {
2257                                 usbi_err(TRANSFER_CTX(transfer),
2258                                         "submiturb failed error %d errno=%d", r, errno);
2259                                 r = LIBUSB_ERROR_IO;
2260                         }
2261
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");
2266                                 free(urbs);
2267                                 tpriv->urbs = NULL;
2268                                 return r;
2269                         }
2270
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
2273                          * complications:
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
2277                          *    freed memory.
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.
2286                          */
2287                         tpriv->reap_action =
2288                                         EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2289
2290                         /* The URBs we haven't submitted yet we count as already
2291                          * retired. */
2292                         tpriv->num_retired += num_urbs - i;
2293
2294                         /* If we completed short then don't try to discard. */
2295                         if (COMPLETED_EARLY == tpriv->reap_action)
2296                                 return LIBUSB_SUCCESS;
2297
2298                         discard_urbs(itransfer, 0, i);
2299
2300                         usbi_dbg("reporting successful submission but waiting for %d "
2301                                 "discards before reporting error", i);
2302                         return LIBUSB_SUCCESS;
2303                 }
2304         }
2305
2306         return LIBUSB_SUCCESS;
2307 }
2308
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;
2314         size_t alloc_size;
2315         const int num_packets = transfer->num_iso_packets;
2316         int i;
2317         int this_urb_len = 0;
2318         int num_urbs = 1;
2319         int packet_offset = 0;
2320         unsigned int packet_len;
2321         unsigned char *urb_buffer = transfer->buffer;
2322
2323         if (UNLIKELY(tpriv->iso_urbs))
2324                 return LIBUSB_ERROR_BUSY;
2325
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.
2330          *
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.
2335          */
2336
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;
2341
2342                 if (packet_len > space_remaining) {
2343                         num_urbs++;
2344                         this_urb_len = packet_len;
2345                 } else {
2346                         this_urb_len += packet_len;
2347                 }
2348         }
2349         usbi_dbg("need %d of 32k URBs for transfer", num_urbs);
2350
2351         alloc_size = num_urbs * sizeof(*urbs);
2352         urbs = calloc(1, alloc_size);
2353         if (UNLIKELY(!urbs))
2354                 return LIBUSB_ERROR_NO_MEM;
2355
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;
2361
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;
2368                 int j;
2369                 int k;
2370
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) {
2375                                 /* throw it in */
2376                                 urb_packet_offset++;
2377                                 packet_offset++;
2378                                 space_remaining_in_urb -= packet_len;
2379                                 urb_buffer += packet_len;
2380                         } else {
2381                                 /* it can't fit, save it for the next URB */
2382                                 break;
2383                         }
2384                 }
2385
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;
2392                 }
2393                 urbs[i] = urb;
2394
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;
2400                 }
2401
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;
2409         }
2410
2411         /* submit URBs */
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;
2417                         } else {
2418                                 usbi_err(TRANSFER_CTX(transfer),
2419                                         "submiturb failed error %d errno=%d", r, errno);
2420                                 r = LIBUSB_ERROR_IO;
2421                         }
2422
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);
2428                                 return r;
2429                         }
2430
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
2433                          * complications:
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
2437                          *    freed memory.
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.
2443                          */
2444                         tpriv->reap_action = SUBMIT_FAILED;
2445
2446                         /* The URBs we haven't submitted yet we count as already
2447                          * retired. */
2448                         tpriv->num_retired = num_urbs - i;
2449                         discard_urbs(itransfer, 0, i);
2450
2451                         usbi_dbg("reporting successful submission but waiting for %d "
2452                                 "discards before reporting error", i);
2453                         return LIBUSB_SUCCESS;
2454                 }
2455         }
2456
2457         return LIBUSB_SUCCESS;
2458 }
2459
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;
2467         int r;
2468
2469         if (UNLIKELY(tpriv->urbs))
2470                 return LIBUSB_ERROR_BUSY;
2471
2472         if (UNLIKELY(transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH))
2473                 return LIBUSB_ERROR_INVALID_PARAM;
2474
2475         urb = calloc(1, sizeof(struct usbfs_urb));
2476         if (UNLIKELY(!urb))
2477                 return LIBUSB_ERROR_NO_MEM;
2478         tpriv->urbs = urb;
2479         tpriv->num_urbs = 1;
2480         tpriv->reap_action = NORMAL;
2481
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;
2487
2488         r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2489         if (UNLIKELY(r < 0)) {
2490                 free(urb);
2491                 tpriv->urbs = NULL;
2492                 if (errno == ENODEV)
2493                         return LIBUSB_ERROR_NO_DEVICE;
2494
2495                 usbi_err(TRANSFER_CTX(transfer),
2496                         "submiturb failed error %d errno=%d", r, errno);
2497                 return LIBUSB_ERROR_IO;
2498         }
2499         return LIBUSB_SUCCESS;
2500 }
2501
2502 static int op_submit_transfer(struct usbi_transfer *itransfer) {
2503         struct libusb_transfer *transfer
2504                 = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2505
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);
2516         default:
2517                 usbi_err(TRANSFER_CTX(transfer),
2518                         "unknown endpoint type %d", transfer->type);
2519                 return LIBUSB_ERROR_INVALID_PARAM;
2520         }
2521 }
2522
2523 static int op_cancel_transfer(struct usbi_transfer *itransfer) {
2524         ENTER();
2525         struct android_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2526         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2527
2528         switch (transfer->type) {
2529         case LIBUSB_TRANSFER_TYPE_BULK:
2530         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2531                 if (tpriv->reap_action == ERROR)
2532                         break;
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;
2538                 break;
2539         default:
2540                 usbi_err(TRANSFER_CTX(transfer),
2541                         "unknown endpoint type %d", transfer->type);
2542                 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
2543         }
2544
2545         if (UNLIKELY(!tpriv->urbs))
2546                 RETURN(LIBUSB_ERROR_NOT_FOUND, int);
2547
2548         RETURN(discard_urbs(itransfer, 0, tpriv->num_urbs), int);
2549 }
2550
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);
2554
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);
2562                 if (tpriv->urbs)
2563                         free(tpriv->urbs);
2564                 tpriv->urbs = NULL;
2565                 usbi_mutex_unlock(&itransfer->lock);
2566                 break;
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);
2572                 break;
2573         default:
2574                 usbi_err(TRANSFER_CTX(transfer),
2575                         "unknown endpoint type %d", transfer->type);
2576         }
2577 }
2578
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;
2585
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);
2589
2590         tpriv->num_retired++;
2591
2592         if (UNLIKELY(tpriv->reap_action != NORMAL)) {
2593                 /* cancelled, submit_fail, or completed early */
2594                 usbi_dbg("abnormal reap: urb status %d", urb->status);
2595
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.
2598                  * examples:
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.)
2606                  *
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.
2611                  */
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);
2620                         }
2621                         itransfer->transferred += urb->actual_length;
2622                 }
2623
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;
2629                         goto completed;
2630                 }
2631                 goto out_unlock;
2632         }
2633
2634         itransfer->transferred += urb->actual_length;
2635
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.
2638          */
2639         switch (urb->status) {
2640         case 0:
2641                 break;
2642         case -EREMOTEIO: /* short transfer */
2643                 break;
2644         case -ENOENT: /* cancelled */
2645         case -ECONNRESET:
2646                 break;
2647         case -ENODEV:
2648         case -ESHUTDOWN:
2649                 usbi_dbg("device removed");
2650                 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2651                 goto cancel_remaining;
2652         case -EPIPE:
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;
2659         case -EOVERFLOW:
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;
2664                 goto completed;
2665         case -ETIME:
2666         case -EPROTO:
2667         case -EILSEQ:
2668         case -ECOMM:
2669         case -ENOSR:
2670                 usbi_dbg("low level error %d", urb->status);
2671                 tpriv->reap_action = ERROR;
2672                 goto cancel_remaining;
2673         default:
2674                 usbi_warn(ITRANSFER_CTX(itransfer),
2675                         "unrecognised urb status %d", urb->status);
2676                 tpriv->reap_action = ERROR;
2677                 goto cancel_remaining;
2678         }
2679
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!");
2683                 goto completed;
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;
2689         } else
2690                 goto out_unlock;
2691
2692 cancel_remaining:
2693         if (ERROR == tpriv->reap_action
2694                         && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2695                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2696
2697         if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2698                 goto completed;
2699
2700         /* cancel remaining urbs and wait for their completion before reporting results */
2701         discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2702
2703 out_unlock:
2704         usbi_mutex_unlock(&itransfer->lock);
2705         return LIBUSB_SUCCESS;
2706
2707 completed:
2708         if (tpriv->urbs)
2709                 free(tpriv->urbs);
2710         tpriv->urbs = NULL;
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);
2715 }
2716
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;
2723         int urb_idx = 0;
2724         int i;
2725         enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2726
2727         usbi_mutex_lock(&itransfer->lock);
2728         for (i = 0; i < num_urbs; i++) {
2729                 if (urb == tpriv->iso_urbs[i]) {
2730                         urb_idx = i + 1;
2731                         break;
2732                 }
2733         }
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;
2738         }
2739
2740         usbi_dbg("handling completion status %d of iso urb %d/%d",
2741                 urb->status, urb_idx, num_urbs);
2742
2743         /* copy isochronous results back in */
2744
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) {
2751                 case 0:
2752                         break;
2753                 case -ENOENT: /* cancelled */
2754                 case -ECONNRESET:
2755                         break;
2756                 case -ENODEV:
2757                 case -ESHUTDOWN:
2758                         usbi_dbg("device removed");
2759                         lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2760                         break;
2761                 case -EPIPE:
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
2766                         break;
2767                 case -EOVERFLOW:
2768                         usbi_dbg("overflow error");
2769                         lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2770                         break;
2771                 case -ETIME:
2772                 case -EPROTO:
2773                 case -EILSEQ:
2774                 case -ECOMM:
2775                 case -ENOSR:
2776                 case -EXDEV:
2777                         usbi_dbg("low-level USB error %d", urb_desc->status);
2778                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2779                         break;
2780                 default:
2781                         usbi_warn(TRANSFER_CTX(transfer),
2782                                 "unrecognised urb status %d", urb_desc->status);
2783                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2784                         break;
2785                 }
2786                 lib_desc->actual_length = urb_desc->actual_length;
2787         }
2788
2789         tpriv->num_retired++;
2790
2791         if (UNLIKELY(tpriv->reap_action != NORMAL)) { /* cancelled or submit_fail */
2792                 usbi_dbg("CANCEL: urb status %d", urb->status);
2793
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);
2800                         } else {
2801                                 usbi_mutex_unlock(&itransfer->lock);
2802                                 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2803                         }
2804                 }
2805                 goto out;
2806         }
2807
2808         switch (urb->status) {
2809         case 0:
2810                 break;
2811         case -ENOENT: /* cancelled */
2812         case -ECONNRESET:
2813                 break;
2814         case -ESHUTDOWN:
2815                 usbi_dbg("device removed");
2816                 status = LIBUSB_TRANSFER_NO_DEVICE;
2817                 break;
2818         default:
2819                 usbi_warn(TRANSFER_CTX(transfer),
2820                         "unrecognised urb status %d", urb->status);
2821                 status = LIBUSB_TRANSFER_ERROR;
2822                 break;
2823         }
2824
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);
2831         }
2832
2833 out:
2834         usbi_mutex_unlock(&itransfer->lock);
2835         return LIBUSB_SUCCESS;
2836 }
2837
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);
2842         int status;
2843
2844         usbi_mutex_lock(&itransfer->lock);
2845         usbi_dbg("handling completion status %d", urb->status);
2846
2847         itransfer->transferred += urb->actual_length;
2848
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);
2853                 if (tpriv->urbs) {
2854                         free(tpriv->urbs);
2855                         tpriv->urbs = NULL;
2856                 }
2857                 usbi_mutex_unlock(&itransfer->lock);
2858                 return usbi_handle_transfer_cancellation(itransfer);
2859         }
2860
2861         switch (urb->status) {
2862         case 0:
2863                 status = LIBUSB_TRANSFER_COMPLETED;
2864                 break;
2865         case -ENOENT: /* cancelled */
2866                 status = LIBUSB_TRANSFER_CANCELLED;
2867                 break;
2868         case -ENODEV:
2869         case -ESHUTDOWN:
2870                 usbi_dbg("device removed");
2871                 status = LIBUSB_TRANSFER_NO_DEVICE;
2872                 break;
2873         case -EPIPE:
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
2878                 break;
2879         case -EOVERFLOW:
2880                 usbi_dbg("control overflow error");
2881                 status = LIBUSB_TRANSFER_OVERFLOW;
2882                 break;
2883         case -ETIME:
2884         case -EPROTO:
2885         case -EILSEQ:
2886         case -ECOMM:
2887         case -ENOSR:
2888                 usbi_dbg("low-level bus error occurred");
2889                 status = LIBUSB_TRANSFER_ERROR;
2890                 break;
2891         default:
2892                 usbi_warn(ITRANSFER_CTX(itransfer),
2893                         "unrecognised urb status %d", urb->status);
2894                 status = LIBUSB_TRANSFER_ERROR;
2895                 break;
2896         }
2897
2898         if (tpriv->urbs) {
2899                 free(tpriv->urbs);      // crash
2900                 tpriv->urbs = NULL;
2901         }
2902         usbi_mutex_unlock(&itransfer->lock);
2903         return usbi_handle_transfer_completion(itransfer, status);
2904 }
2905
2906 static int reap_for_handle(struct libusb_device_handle *handle) {
2907         struct android_device_handle_priv *hpriv = _device_handle_priv(handle);
2908         int r;
2909         struct usbfs_urb *urb;
2910         struct usbi_transfer *itransfer;
2911         struct libusb_transfer *transfer;
2912
2913         r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2914         if (r == -1 && errno == EAGAIN)
2915                 return 1;
2916         if (UNLIKELY(r < 0)) {
2917                 if (errno == ENODEV)
2918                         return LIBUSB_ERROR_NO_DEVICE;
2919
2920                 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d", r, errno);
2921                 return LIBUSB_ERROR_IO;
2922         }
2923
2924         itransfer = urb->usercontext;
2925         transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2926
2927         usbi_dbg("urb type=%d status=%d transferred=%d",
2928                 urb->type, urb->status, urb->actual_length);
2929
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);
2939         default:
2940                 usbi_err(HANDLE_CTX(handle),
2941                         "unrecognised endpoint type %x", transfer->type);
2942                 return LIBUSB_ERROR_OTHER;
2943         }
2944 }
2945
2946 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds,
2947                 POLL_NFDS_TYPE nfds, int num_ready) {
2948         int r;
2949         unsigned int i = 0;
2950
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;
2956
2957                 if (!pollfd->revents)
2958                         continue;
2959
2960                 num_ready--;
2961                 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle)
2962                 {
2963                         hpriv = _device_handle_priv(handle);
2964                         if (hpriv->fd == pollfd->fd)
2965                                 break;
2966                 }
2967
2968                 if (!hpriv || hpriv->fd != pollfd->fd) {
2969                         usbi_err(ctx, "cannot find handle for fd %d\n",
2970                                  pollfd->fd);
2971                         continue;
2972                 }
2973
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);
2986                         continue;
2987                 }
2988
2989                 do {
2990                         r = reap_for_handle(handle);
2991                 } while (r == 0);
2992                 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2993                         continue;
2994                 else if (r < 0)
2995                         goto out;
2996         }
2997
2998         r = 0;
2999 out:
3000         usbi_mutex_unlock(&ctx->open_devs_lock);
3001         return r;
3002 }
3003
3004 static int op_clock_gettime(int clk_id, struct timespec *tp) {
3005         switch (clk_id) {
3006         case USBI_CLOCK_MONOTONIC:
3007                 return clock_gettime(monotonic_clkid, tp);
3008         case USBI_CLOCK_REALTIME:
3009                 return clock_gettime(CLOCK_REALTIME, tp);
3010         default:
3011                 return LIBUSB_ERROR_INVALID_PARAM;
3012         }
3013 }
3014
3015 #ifdef USBI_TIMERFD_AVAILABLE
3016 static clockid_t op_get_timerfd_clockid(void)
3017 {
3018         return monotonic_clkid;
3019
3020 }
3021 #endif
3022
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,
3026         .init = op_init,
3027         .init2 = op_init2,      // XXX
3028         .exit = op_exit,
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
3037         .open = op_open,
3038         .close = op_close,
3039         .get_configuration = op_get_configuration,
3040         .set_configuration = op_set_configuration,
3041         .claim_interface = op_claim_interface,
3042         .release_interface = op_release_interface,
3043
3044         .set_interface_altsetting = op_set_interface,
3045         .clear_halt = op_clear_halt,
3046         .reset_device = op_reset_device,
3047
3048         .alloc_streams = op_alloc_streams,
3049         .free_streams = op_free_streams,
3050
3051         .kernel_driver_active = op_kernel_driver_active,
3052         .detach_kernel_driver = op_detach_kernel_driver,
3053         .attach_kernel_driver = op_attach_kernel_driver,
3054
3055         .destroy_device = op_destroy_device,
3056
3057         .submit_transfer = op_submit_transfer,
3058         .cancel_transfer = op_cancel_transfer,
3059         .clear_transfer_priv = op_clear_transfer_priv,
3060
3061         .handle_events = op_handle_events,
3062
3063         .clock_gettime = op_clock_gettime,
3064
3065 #ifdef USBI_TIMERFD_AVAILABLE
3066         .get_timerfd_clockid = op_get_timerfd_clockid,
3067 #endif
3068
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,
3073 };