Merge branch 'dev' v0.3.0
[rtmpclient.git] / app / src / main / jni / libusb-1.0.22 / libusb / os / linux_usbfs.c
1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
2 /*
3  * Linux usbfs backend for libusb
4  * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6  * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7  * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <ctype.h>
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <poll.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/ioctl.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
40 #include <time.h>
41
42 #include "libusbi.h"
43 #include "linux_usbfs.h"
44
45 /* sysfs vs usbfs:
46  * opening a usbfs node causes the device to be resumed, so we attempt to
47  * avoid this during enumeration.
48  *
49  * sysfs allows us to read the kernel's in-memory copies of device descriptors
50  * and so forth, avoiding the need to open the device:
51  *  - The binary "descriptors" file contains all config descriptors since
52  *    2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
53  *  - The binary "descriptors" file was added in 2.6.23, commit
54  *    69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
55  *    active config descriptors
56  *  - The "busnum" file was added in 2.6.22, commit
57  *    83f7d958eab2fbc6b159ee92bf1493924e1d0f72
58  *  - The "devnum" file has been present since pre-2.6.18
59  *  - the "bConfigurationValue" file has been present since pre-2.6.18
60  *
61  * If we have bConfigurationValue, busnum, and devnum, then we can determine
62  * the active configuration without having to open the usbfs node in RDWR mode.
63  * The busnum file is important as that is the only way we can relate sysfs
64  * devices to usbfs nodes.
65  *
66  * If we also have all descriptors, we can obtain the device descriptor and
67  * configuration without touching usbfs at all.
68  */
69
70 /* endianness for multi-byte fields:
71  *
72  * Descriptors exposed by usbfs have the multi-byte fields in the device
73  * descriptor as host endian. Multi-byte fields in the other descriptors are
74  * bus-endian. The kernel documentation says otherwise, but it is wrong.
75  *
76  * In sysfs all descriptors are bus-endian.
77  */
78
79 static const char *usbfs_path = NULL;
80
81 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
82 static int usbdev_names = 0;
83
84 /* Linux has changed the maximum length of an individual isochronous packet
85  * over time.  Initially this limit was 1,023 bytes, but Linux 2.6.18
86  * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
87  * 8,192 bytes to support higher bandwidth devices.  Linux 3.10
88  * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
89  * value to 49,152 bytes to support super speed devices.
90  */
91 static unsigned int max_iso_packet_len = 0;
92
93 /* Linux 2.6.23 adds support for O_CLOEXEC when opening files, which marks the
94  * close-on-exec flag in the underlying file descriptor. */
95 static int supports_flag_cloexec = -1;
96
97 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
98  * allows us to mark URBs as being part of a specific logical transfer when
99  * we submit them to the kernel. then, on any error except a cancellation, all
100  * URBs within that transfer will be cancelled and no more URBs will be
101  * accepted for the transfer, meaning that no more data can creep in.
102  *
103  * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
104  * (in either direction) except the first.
105  * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
106  * last; it means that the kernel should treat a short reply as an error.
107  * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
108  * transfers can't be short unless there's already some sort of error), and
109  * setting this flag is disallowed (a kernel with USB debugging enabled will
110  * reject such URBs).
111  */
112 static int supports_flag_bulk_continuation = -1;
113
114 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
115  * allows us to mark URBs that should be followed by a zero length data
116  * packet, which can be required by device- or class-specific protocols.
117  */
118 static int supports_flag_zero_packet = -1;
119
120 /* clock ID for monotonic clock, as not all clock sources are available on all
121  * systems. appropriate choice made at initialization time. */
122 static clockid_t monotonic_clkid = -1;
123
124 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
125  * to sysfs, so we can relate devices. This also implies that we can read
126  * the active configuration through bConfigurationValue */
127 static int sysfs_can_relate_devices = -1;
128
129 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
130  * config descriptors (rather then just the active config) to the sysfs
131  * descriptors file, so from then on we can use them. */
132 static int sysfs_has_descriptors = -1;
133
134 /* how many times have we initted (and not exited) ? */
135 static int init_count = 0;
136
137 /* Serialize hotplug start/stop */
138 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
139 /* Serialize scan-devices, event-thread, and poll */
140 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
141
142 static int linux_start_event_monitor(void);
143 static int linux_stop_event_monitor(void);
144 static int linux_scan_devices(struct libusb_context *ctx);
145 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
146 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
147
148 #if !defined(USE_UDEV)
149 static int linux_default_scan_devices (struct libusb_context *ctx);
150 #endif
151
152 struct kernel_version {
153         int major;
154         int minor;
155         int sublevel;
156 };
157
158 struct linux_device_priv {
159         char *sysfs_dir;
160         unsigned char *descriptors;
161         int descriptors_len;
162         int active_config; /* cache val for !sysfs_can_relate_devices  */
163     int fd;
164 };
165
166 struct linux_device_handle_priv {
167         int fd;
168         int fd_removed;
169         uint32_t caps;
170 };
171
172 enum reap_action {
173         NORMAL = 0,
174         /* submission failed after the first URB, so await cancellation/completion
175          * of all the others */
176         SUBMIT_FAILED,
177
178         /* cancelled by user or timeout */
179         CANCELLED,
180
181         /* completed multi-URB transfer in non-final URB */
182         COMPLETED_EARLY,
183
184         /* one or more urbs encountered a low-level error */
185         ERROR,
186 };
187
188 struct linux_transfer_priv {
189         union {
190                 struct usbfs_urb *urbs;
191                 struct usbfs_urb **iso_urbs;
192         };
193
194         enum reap_action reap_action;
195         int num_urbs;
196         int num_retired;
197         enum libusb_transfer_status reap_status;
198
199         /* next iso packet in user-supplied transfer to be populated */
200         int iso_packet_offset;
201 };
202
203 static int _open(const char *path, int flags)
204 {
205 #if defined(O_CLOEXEC)
206         if (supports_flag_cloexec)
207                 return open(path, flags | O_CLOEXEC);
208         else
209 #endif
210                 return open(path, flags);
211 }
212
213 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
214 {
215         struct libusb_context *ctx = DEVICE_CTX(dev);
216         char path[PATH_MAX];
217         int fd;
218         int delay = 10000;
219
220         if (usbdev_names)
221                 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
222                         usbfs_path, dev->bus_number, dev->device_address);
223         else
224                 snprintf(path, PATH_MAX, "%s/%03d/%03d",
225                         usbfs_path, dev->bus_number, dev->device_address);
226
227         fd = _open(path, mode);
228         if (fd != -1)
229                 return fd; /* Success */
230
231         if (errno == ENOENT) {
232                 if (!silent) 
233                         usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
234    
235                 /* Wait 10ms for USB device path creation.*/
236                 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
237
238                 fd = _open(path, mode);
239                 if (fd != -1)
240                         return fd; /* Success */
241         }
242         
243         if (!silent) {
244                 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
245                          path, strerror(errno));
246                 if (errno == EACCES && mode == O_RDWR)
247                         usbi_err(ctx, "libusb requires write access to USB "
248                                       "device nodes.");
249         }
250
251         if (errno == EACCES)
252                 return LIBUSB_ERROR_ACCESS;
253         if (errno == ENOENT)
254                 return LIBUSB_ERROR_NO_DEVICE;
255         return LIBUSB_ERROR_IO;
256 }
257
258 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
259 {
260         return (struct linux_device_priv *) dev->os_priv;
261 }
262
263 static struct linux_device_handle_priv *_device_handle_priv(
264         struct libusb_device_handle *handle)
265 {
266         return (struct linux_device_handle_priv *) handle->os_priv;
267 }
268
269 /* check dirent for a /dev/usbdev%d.%d name
270  * optionally return bus/device on success */
271 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
272 {
273         int busnum, devnum;
274
275         if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
276                 return 0;
277
278         usbi_dbg("found: %s", entry->d_name);
279         if (bus_p != NULL)
280                 *bus_p = busnum;
281         if (dev_p != NULL)
282                 *dev_p = devnum;
283         return 1;
284 }
285
286 static int check_usb_vfs(const char *dirname)
287 {
288         DIR *dir;
289         struct dirent *entry;
290         int found = 0;
291
292         dir = opendir(dirname);
293         if (!dir)
294                 return 0;
295
296         while ((entry = readdir(dir)) != NULL) {
297                 if (entry->d_name[0] == '.')
298                         continue;
299
300                 /* We assume if we find any files that it must be the right place */
301                 found = 1;
302                 break;
303         }
304
305         closedir(dir);
306         return found;
307 }
308
309 static const char *find_usbfs_path(void)
310 {
311         const char *path = "/dev/bus/usb";
312         const char *ret = NULL;
313
314         if (check_usb_vfs(path)) {
315                 ret = path;
316         } else {
317                 path = "/proc/bus/usb";
318                 if (check_usb_vfs(path))
319                         ret = path;
320         }
321
322         /* look for /dev/usbdev*.* if the normal places fail */
323         if (ret == NULL) {
324                 struct dirent *entry;
325                 DIR *dir;
326
327                 path = "/dev";
328                 dir = opendir(path);
329                 if (dir != NULL) {
330                         while ((entry = readdir(dir)) != NULL) {
331                                 if (_is_usbdev_entry(entry, NULL, NULL)) {
332                                         /* found one; that's enough */
333                                         ret = path;
334                                         usbdev_names = 1;
335                                         break;
336                                 }
337                         }
338                         closedir(dir);
339                 }
340         }
341
342 /* On udev based systems without any usb-devices /dev/bus/usb will not
343  * exist. So if we've not found anything and we're using udev for hotplug
344  * simply assume /dev/bus/usb rather then making libusb_init fail. */
345 #if defined(USE_UDEV)
346         if (ret == NULL)
347                 ret = "/dev/bus/usb";
348 #endif
349
350         if (ret != NULL)
351                 usbi_dbg("found usbfs at %s", ret);
352
353         return ret;
354 }
355
356 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
357  * seem to lack it). fall back to REALTIME if we have to. */
358 static clockid_t find_monotonic_clock(void)
359 {
360 #ifdef CLOCK_MONOTONIC
361         struct timespec ts;
362         int r;
363
364         /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
365          * because it's not available through timerfd */
366         r = clock_gettime(CLOCK_MONOTONIC, &ts);
367         if (r == 0)
368                 return CLOCK_MONOTONIC;
369         usbi_dbg("monotonic clock doesn't work, errno %d", errno);
370 #endif
371
372         return CLOCK_REALTIME;
373 }
374
375 static int get_kernel_version(struct libusb_context *ctx,
376         struct kernel_version *ver)
377 {
378         struct utsname uts;
379         int atoms;
380
381         if (uname(&uts) < 0) {
382                 usbi_err(ctx, "uname failed, errno %d", errno);
383                 return -1;
384         }
385
386         atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
387         if (atoms < 1) {
388                 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
389                 return -1;
390         }
391
392         if (atoms < 2)
393                 ver->minor = -1;
394         if (atoms < 3)
395                 ver->sublevel = -1;
396
397         usbi_dbg("reported kernel version is %s", uts.release);
398
399         return 0;
400 }
401
402 static int kernel_version_ge(const struct kernel_version *ver,
403         int major, int minor, int sublevel)
404 {
405         if (ver->major > major)
406                 return 1;
407         else if (ver->major < major)
408                 return 0;
409
410         /* kmajor == major */
411         if (ver->minor == -1 && ver->sublevel == -1)
412                 return 0 == minor && 0 == sublevel;
413         else if (ver->minor > minor)
414                 return 1;
415         else if (ver->minor < minor)
416                 return 0;
417
418         /* kminor == minor */
419         if (ver->sublevel == -1)
420                 return 0 == sublevel;
421
422         return ver->sublevel >= sublevel;
423 }
424
425 static int op_init(struct libusb_context *ctx)
426 {
427         struct kernel_version kversion;
428         struct stat statbuf;
429         int r;
430
431         usbfs_path = find_usbfs_path();
432         if (!usbfs_path) {
433                 usbi_err(ctx, "could not find usbfs");
434                 return LIBUSB_ERROR_OTHER;
435         }
436
437         if (monotonic_clkid == -1)
438                 monotonic_clkid = find_monotonic_clock();
439
440         if (get_kernel_version(ctx, &kversion) < 0)
441                 return LIBUSB_ERROR_OTHER;
442
443         if (supports_flag_cloexec == -1) {
444                 /* O_CLOEXEC flag available from Linux 2.6.23 */
445                 supports_flag_cloexec = kernel_version_ge(&kversion,2,6,23);
446         }
447
448         if (supports_flag_bulk_continuation == -1) {
449                 /* bulk continuation URB flag available from Linux 2.6.32 */
450                 supports_flag_bulk_continuation = kernel_version_ge(&kversion,2,6,32);
451         }
452
453         if (supports_flag_bulk_continuation)
454                 usbi_dbg("bulk continuation flag supported");
455
456         if (-1 == supports_flag_zero_packet) {
457                 /* zero length packet URB flag fixed since Linux 2.6.31 */
458                 supports_flag_zero_packet = kernel_version_ge(&kversion,2,6,31);
459         }
460
461         if (supports_flag_zero_packet)
462                 usbi_dbg("zero length packet flag supported");
463
464         if (!max_iso_packet_len) {
465                 if (kernel_version_ge(&kversion,3,10,0))
466                         max_iso_packet_len = 49152;
467                 else if (kernel_version_ge(&kversion,2,6,18))
468                         max_iso_packet_len = 8192;
469                 else
470                         max_iso_packet_len = 1023;
471         }
472
473         usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
474
475         if (-1 == sysfs_has_descriptors) {
476                 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
477                 sysfs_has_descriptors = kernel_version_ge(&kversion,2,6,26);
478         }
479
480         if (-1 == sysfs_can_relate_devices) {
481                 /* sysfs has busnum since Linux 2.6.22 */
482                 sysfs_can_relate_devices = kernel_version_ge(&kversion,2,6,22);
483         }
484
485         if (sysfs_can_relate_devices || sysfs_has_descriptors) {
486                 r = stat(SYSFS_DEVICE_PATH, &statbuf);
487                 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
488                         usbi_warn(ctx, "sysfs not mounted");
489                         sysfs_can_relate_devices = 0;
490                         sysfs_has_descriptors = 0;
491                 }
492         }
493
494         if (sysfs_can_relate_devices)
495                 usbi_dbg("sysfs can relate devices");
496
497         if (sysfs_has_descriptors)
498                 usbi_dbg("sysfs has complete descriptors");
499
500         usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
501         r = LIBUSB_SUCCESS;
502         if (init_count == 0) {
503                 /* start up hotplug event handler */
504                 r = linux_start_event_monitor();
505         }
506         if (r == LIBUSB_SUCCESS) {
507                 r = linux_scan_devices(ctx);
508                 if (r == LIBUSB_SUCCESS)
509                         init_count++;
510                 else if (init_count == 0)
511                         linux_stop_event_monitor();
512         } else
513                 usbi_err(ctx, "error starting hotplug event monitor");
514         usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
515
516         return r;
517 }
518
519 static void op_exit(struct libusb_context *ctx)
520 {
521         UNUSED(ctx);
522         usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
523         assert(init_count != 0);
524         if (!--init_count) {
525                 /* tear down event handler */
526                 (void)linux_stop_event_monitor();
527         }
528         usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
529 }
530
531 static int linux_start_event_monitor(void)
532 {
533 #if defined(USE_UDEV)
534         return linux_udev_start_event_monitor();
535 #else
536         return linux_netlink_start_event_monitor();
537 #endif
538 }
539
540 static int linux_stop_event_monitor(void)
541 {
542 #if defined(USE_UDEV)
543         return linux_udev_stop_event_monitor();
544 #else
545         return linux_netlink_stop_event_monitor();
546 #endif
547 }
548
549 static int linux_scan_devices(struct libusb_context *ctx)
550 {
551         int ret;
552
553         usbi_mutex_static_lock(&linux_hotplug_lock);
554
555 #if defined(USE_UDEV)
556         ret = linux_udev_scan_devices(ctx);
557 #else
558         ret = linux_default_scan_devices(ctx);
559 #endif
560
561         usbi_mutex_static_unlock(&linux_hotplug_lock);
562
563         return ret;
564 }
565
566 static void op_hotplug_poll(void)
567 {
568 #if defined(USE_UDEV)
569         linux_udev_hotplug_poll();
570 #else
571         linux_netlink_hotplug_poll();
572 #endif
573 }
574
575 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
576 {
577         struct linux_device_priv *priv = _device_priv(dev);
578         char filename[PATH_MAX];
579         int fd;
580
581         snprintf(filename, PATH_MAX, "%s/%s/%s",
582                 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
583         fd = _open(filename, O_RDONLY);
584         if (fd < 0) {
585                 usbi_err(DEVICE_CTX(dev),
586                         "open %s failed ret=%d errno=%d", filename, fd, errno);
587                 return LIBUSB_ERROR_IO;
588         }
589
590         return fd;
591 }
592
593 /* Note only suitable for attributes which always read >= 0, < 0 is error */
594 static int __read_sysfs_attr(struct libusb_context *ctx,
595         const char *devname, const char *attr)
596 {
597         char filename[PATH_MAX];
598         FILE *f;
599         int fd, r, value;
600
601         snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
602                  devname, attr);
603         fd = _open(filename, O_RDONLY);
604         if (fd == -1) {
605                 if (errno == ENOENT) {
606                         /* File doesn't exist. Assume the device has been
607                            disconnected (see trac ticket #70). */
608                         return LIBUSB_ERROR_NO_DEVICE;
609                 }
610                 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
611                 return LIBUSB_ERROR_IO;
612         }
613
614         f = fdopen(fd, "r");
615         if (f == NULL) {
616                 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
617                 close(fd);
618                 return LIBUSB_ERROR_OTHER;
619         }
620
621         r = fscanf(f, "%d", &value);
622         fclose(f);
623         if (r != 1) {
624                 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
625                 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
626         }
627         if (value < 0) {
628                 usbi_err(ctx, "%s contains a negative value", filename);
629                 return LIBUSB_ERROR_IO;
630         }
631
632         return value;
633 }
634
635 static int op_get_device_descriptor(struct libusb_device *dev,
636         unsigned char *buffer, int *host_endian)
637 {
638         struct linux_device_priv *priv = _device_priv(dev);
639
640         *host_endian = sysfs_has_descriptors ? 0 : 1;
641         memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
642
643         return 0;
644 }
645
646 /* read the bConfigurationValue for a device */
647 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
648 {
649         char *endptr;
650         char tmp[5] = {0, 0, 0, 0, 0};
651         long num;
652         int fd;
653         ssize_t r;
654
655         fd = _open_sysfs_attr(dev, "bConfigurationValue");
656         if (fd < 0)
657                 return fd;
658
659         r = read(fd, tmp, sizeof(tmp));
660         close(fd);
661         if (r < 0) {
662                 usbi_err(DEVICE_CTX(dev),
663                         "read bConfigurationValue failed ret=%d errno=%d", r, errno);
664                 return LIBUSB_ERROR_IO;
665         } else if (r == 0) {
666                 usbi_dbg("device unconfigured");
667                 *config = -1;
668                 return 0;
669         }
670
671         if (tmp[sizeof(tmp) - 1] != 0) {
672                 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
673                 return LIBUSB_ERROR_IO;
674         } else if (tmp[0] == 0) {
675                 usbi_err(DEVICE_CTX(dev), "no configuration value?");
676                 return LIBUSB_ERROR_IO;
677         }
678
679         num = strtol(tmp, &endptr, 10);
680         if (endptr == tmp) {
681                 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
682                 return LIBUSB_ERROR_IO;
683         }
684
685         *config = (int) num;
686         return 0;
687 }
688
689 int linux_get_device_address (struct libusb_context *ctx, int detached,
690         uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
691         const char *sys_name)
692 {
693         int sysfs_attr;
694
695         usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
696         /* can't use sysfs to read the bus and device number if the
697          * device has been detached */
698         if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
699                 if (NULL == dev_node) {
700                         return LIBUSB_ERROR_OTHER;
701                 }
702
703                 /* will this work with all supported kernel versions? */
704                 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
705                         sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
706                 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
707                         sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
708                 }
709
710                 return LIBUSB_SUCCESS;
711         }
712
713         usbi_dbg("scan %s", sys_name);
714
715         sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
716         if (0 > sysfs_attr)
717                 return sysfs_attr;
718         if (sysfs_attr > 255)
719                 return LIBUSB_ERROR_INVALID_PARAM;
720         *busnum = (uint8_t) sysfs_attr;
721
722         sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
723         if (0 > sysfs_attr)
724                 return sysfs_attr;
725         if (sysfs_attr > 255)
726                 return LIBUSB_ERROR_INVALID_PARAM;
727
728         *devaddr = (uint8_t) sysfs_attr;
729
730         usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
731
732         return LIBUSB_SUCCESS;
733 }
734
735 /* Return offset of the next descriptor with the given type */
736 static int seek_to_next_descriptor(struct libusb_context *ctx,
737         uint8_t descriptor_type, unsigned char *buffer, int size)
738 {
739         struct usb_descriptor_header header;
740         int i;
741
742         for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
743                 if (size == 0)
744                         return LIBUSB_ERROR_NOT_FOUND;
745
746                 if (size < 2) {
747                         usbi_err(ctx, "short descriptor read %d/2", size);
748                         return LIBUSB_ERROR_IO;
749                 }
750                 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
751
752                 if (i && header.bDescriptorType == descriptor_type)
753                         return i;
754         }
755         usbi_err(ctx, "bLength overflow by %d bytes", -size);
756         return LIBUSB_ERROR_IO;
757 }
758
759 /* Return offset to next config */
760 static int seek_to_next_config(struct libusb_context *ctx,
761         unsigned char *buffer, int size)
762 {
763         struct libusb_config_descriptor config;
764
765         if (size == 0)
766                 return LIBUSB_ERROR_NOT_FOUND;
767
768         if (size < LIBUSB_DT_CONFIG_SIZE) {
769                 usbi_err(ctx, "short descriptor read %d/%d",
770                          size, LIBUSB_DT_CONFIG_SIZE);
771                 return LIBUSB_ERROR_IO;
772         }
773
774         usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
775         if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
776                 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
777                          config.bDescriptorType);
778                 return LIBUSB_ERROR_IO;
779         }
780
781         /*
782          * In usbfs the config descriptors are config.wTotalLength bytes apart,
783          * with any short reads from the device appearing as holes in the file.
784          *
785          * In sysfs wTotalLength is ignored, instead the kernel returns a
786          * config descriptor with verified bLength fields, with descriptors
787          * with an invalid bLength removed.
788          */
789         if (sysfs_has_descriptors) {
790                 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
791                                                    buffer, size);
792                 if (next == LIBUSB_ERROR_NOT_FOUND)
793                         next = size;
794                 if (next < 0)
795                         return next;
796
797                 if (next != config.wTotalLength)
798                         usbi_warn(ctx, "config length mismatch wTotalLength "
799                                   "%d real %d", config.wTotalLength, next);
800                 return next;
801         } else {
802                 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
803                         usbi_err(ctx, "invalid wTotalLength %d",
804                                  config.wTotalLength);
805                         return LIBUSB_ERROR_IO;
806                 } else if (config.wTotalLength > size) {
807                         usbi_warn(ctx, "short descriptor read %d/%d",
808                                   size, config.wTotalLength);
809                         return size;
810                 } else
811                         return config.wTotalLength;
812         }
813 }
814
815 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
816         uint8_t value, unsigned char **buffer, int *host_endian)
817 {
818         struct libusb_context *ctx = DEVICE_CTX(dev);
819         struct linux_device_priv *priv = _device_priv(dev);
820         unsigned char *descriptors = priv->descriptors;
821         int size = priv->descriptors_len;
822         struct libusb_config_descriptor *config;
823
824         *buffer = NULL;
825         /* Unlike the device desc. config descs. are always in raw format */
826         *host_endian = 0;
827
828         /* Skip device header */
829         descriptors += DEVICE_DESC_LENGTH;
830         size -= DEVICE_DESC_LENGTH;
831
832         /* Seek till the config is found, or till "EOF" */
833         while (1) {
834                 int next = seek_to_next_config(ctx, descriptors, size);
835                 if (next < 0)
836                         return next;
837                 config = (struct libusb_config_descriptor *)descriptors;
838                 if (config->bConfigurationValue == value) {
839                         *buffer = descriptors;
840                         return next;
841                 }
842                 size -= next;
843                 descriptors += next;
844         }
845 }
846
847 static int op_get_active_config_descriptor(struct libusb_device *dev,
848         unsigned char *buffer, size_t len, int *host_endian)
849 {
850         int r, config;
851         unsigned char *config_desc;
852
853         if (sysfs_can_relate_devices) {
854                 r = sysfs_get_active_config(dev, &config);
855                 if (r < 0)
856                         return r;
857         } else {
858                 /* Use cached bConfigurationValue */
859                 struct linux_device_priv *priv = _device_priv(dev);
860                 config = priv->active_config;
861         }
862         if (config == -1)
863                 return LIBUSB_ERROR_NOT_FOUND;
864
865         r = op_get_config_descriptor_by_value(dev, config, &config_desc,
866                                               host_endian);
867         if (r < 0)
868                 return r;
869
870         len = MIN(len, (size_t)r);
871         memcpy(buffer, config_desc, len);
872         return len;
873 }
874
875 static int op_get_config_descriptor(struct libusb_device *dev,
876         uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
877 {
878         struct linux_device_priv *priv = _device_priv(dev);
879         unsigned char *descriptors = priv->descriptors;
880         int i, r, size = priv->descriptors_len;
881
882         /* Unlike the device desc. config descs. are always in raw format */
883         *host_endian = 0;
884
885         /* Skip device header */
886         descriptors += DEVICE_DESC_LENGTH;
887         size -= DEVICE_DESC_LENGTH;
888
889         /* Seek till the config is found, or till "EOF" */
890         for (i = 0; ; i++) {
891                 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
892                 if (r < 0)
893                         return r;
894                 if (i == config_index)
895                         break;
896                 size -= r;
897                 descriptors += r;
898         }
899
900         len = MIN(len, (size_t)r);
901         memcpy(buffer, descriptors, len);
902         return len;
903 }
904
905 /* send a control message to retrieve active configuration */
906 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
907 {
908         struct linux_device_priv *priv = _device_priv(dev);
909         unsigned char active_config = 0;
910         int r;
911
912         struct usbfs_ctrltransfer ctrl = {
913                 .bmRequestType = LIBUSB_ENDPOINT_IN,
914                 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
915                 .wValue = 0,
916                 .wIndex = 0,
917                 .wLength = 1,
918                 .timeout = 1000,
919                 .data = &active_config
920         };
921
922         r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
923         if (r < 0) {
924                 if (errno == ENODEV)
925                         return LIBUSB_ERROR_NO_DEVICE;
926
927                 /* we hit this error path frequently with buggy devices :( */
928                 usbi_warn(DEVICE_CTX(dev),
929                         "get_configuration failed ret=%d errno=%d", r, errno);
930                 //priv->active_config = -1;
931         return LIBUSB_ERROR_IO;
932         } 
933 //    else {
934 //              if (active_config > 0) {
935 //                      priv->active_config = active_config;
936 //              } else {
937 //                      /* some buggy devices have a configuration 0, but we're
938 //                       * reaching into the corner of a corner case here, so let's
939 //                       * not support buggy devices in these circumstances.
940 //                       * stick to the specs: a configuration value of 0 means
941 //                       * unconfigured. */
942 //                      usbi_warn(DEVICE_CTX(dev),
943 //                              "active cfg 0? assuming unconfigured device");
944 //                      priv->active_config = -1;
945 //              }
946 //      }
947 //
948     return active_config;
949 //      return LIBUSB_SUCCESS;
950 }
951
952 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
953         uint8_t devaddr, const char *sysfs_dir)
954 {
955         struct linux_device_priv *priv = _device_priv(dev);
956         struct libusb_context *ctx = DEVICE_CTX(dev);
957         int descriptors_size = 512; /* Begin with a 1024 byte alloc */
958         int fd, speed;
959         ssize_t r;
960
961         dev->bus_number = busnum;
962         dev->device_address = devaddr;
963
964         if (sysfs_dir) {
965                 priv->sysfs_dir = strdup(sysfs_dir);
966                 if (!priv->sysfs_dir)
967                         return LIBUSB_ERROR_NO_MEM;
968
969                 /* Note speed can contain 1.5, in this case __read_sysfs_attr
970                    will stop parsing at the '.' and return 1 */
971                 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
972                 if (speed >= 0) {
973                         switch (speed) {
974                         case     1: dev->speed = LIBUSB_SPEED_LOW; break;
975                         case    12: dev->speed = LIBUSB_SPEED_FULL; break;
976                         case   480: dev->speed = LIBUSB_SPEED_HIGH; break;
977                         case  5000: dev->speed = LIBUSB_SPEED_SUPER; break;
978                         case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
979                         default:
980                                 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
981                         }
982                 }
983         }
984
985         /* cache descriptors in memory */
986         if (sysfs_has_descriptors)
987                 fd = _open_sysfs_attr(dev, "descriptors");
988         else
989                 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
990         if (fd < 0)
991                 return fd;
992
993         do {
994                 descriptors_size *= 2;
995                 priv->descriptors = usbi_reallocf(priv->descriptors,
996                                                   descriptors_size);
997                 if (!priv->descriptors) {
998                         close(fd);
999                         return LIBUSB_ERROR_NO_MEM;
1000                 }
1001                 /* usbfs has holes in the file */
1002                 if (!sysfs_has_descriptors) {
1003                         memset(priv->descriptors + priv->descriptors_len,
1004                                0, descriptors_size - priv->descriptors_len);
1005                 }
1006                 r = read(fd, priv->descriptors + priv->descriptors_len,
1007                          descriptors_size - priv->descriptors_len);
1008                 if (r < 0) {
1009                         usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1010                                  fd, errno);
1011                         close(fd);
1012                         return LIBUSB_ERROR_IO;
1013                 }
1014                 priv->descriptors_len += r;
1015         } while (priv->descriptors_len == descriptors_size);
1016
1017         close(fd);
1018
1019         if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1020                 usbi_err(ctx, "short descriptor read (%d)",
1021                          priv->descriptors_len);
1022                 return LIBUSB_ERROR_IO;
1023         }
1024
1025         if (sysfs_can_relate_devices)
1026                 return LIBUSB_SUCCESS;
1027
1028         /* cache active config */
1029         fd = _get_usbfs_fd(dev, O_RDWR, 1);
1030         if (fd < 0) {
1031                 /* cannot send a control message to determine the active
1032                  * config. just assume the first one is active. */
1033                 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1034                                "active configuration descriptor");
1035                 if (priv->descriptors_len >=
1036                                 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1037                         struct libusb_config_descriptor config;
1038                         usbi_parse_descriptor(
1039                                 priv->descriptors + DEVICE_DESC_LENGTH,
1040                                 "bbwbbbbb", &config, 0);
1041                         priv->active_config = config.bConfigurationValue;
1042                 } else
1043                         priv->active_config = -1; /* No config dt */
1044
1045                 return LIBUSB_SUCCESS;
1046         }
1047
1048         r = usbfs_get_active_config(dev, fd);
1049         close(fd);
1050
1051         return r;
1052 }
1053
1054 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1055 {
1056         struct libusb_context *ctx = DEVICE_CTX(dev);
1057         struct libusb_device *it;
1058         char *parent_sysfs_dir, *tmp;
1059         int ret, add_parent = 1;
1060
1061         /* XXX -- can we figure out the topology when using usbfs? */
1062         if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1063                 /* either using usbfs or finding the parent of a root hub */
1064                 return LIBUSB_SUCCESS;
1065         }
1066
1067         parent_sysfs_dir = strdup(sysfs_dir);
1068         if (NULL == parent_sysfs_dir) {
1069                 return LIBUSB_ERROR_NO_MEM;
1070         }
1071         if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1072             NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1073                 dev->port_number = atoi(tmp + 1);
1074                 *tmp = '\0';
1075         } else {
1076                 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1077                           parent_sysfs_dir);
1078                 free (parent_sysfs_dir);
1079                 return LIBUSB_SUCCESS;
1080         }
1081
1082         /* is the parent a root hub? */
1083         if (NULL == strchr(parent_sysfs_dir, '-')) {
1084                 tmp = parent_sysfs_dir;
1085                 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1086                 free (tmp);
1087                 if (0 > ret) {
1088                         return LIBUSB_ERROR_NO_MEM;
1089                 }
1090         }
1091
1092 retry:
1093         /* find the parent in the context */
1094         usbi_mutex_lock(&ctx->usb_devs_lock);
1095         list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1096                 struct linux_device_priv *priv = _device_priv(it);
1097                 if (priv->sysfs_dir) {
1098                         if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1099                                 dev->parent_dev = libusb_ref_device(it);
1100                                 break;
1101                         }
1102                 }
1103         }
1104         usbi_mutex_unlock(&ctx->usb_devs_lock);
1105
1106         if (!dev->parent_dev && add_parent) {
1107                 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1108                          parent_sysfs_dir);
1109                 sysfs_scan_device(ctx, parent_sysfs_dir);
1110                 add_parent = 0;
1111                 goto retry;
1112         }
1113
1114         usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1115                  dev->parent_dev, parent_sysfs_dir, dev->port_number);
1116
1117         free (parent_sysfs_dir);
1118
1119         return LIBUSB_SUCCESS;
1120 }
1121
1122 static int linux_initialize_device(struct libusb_device *dev,
1123         uint8_t busnum, uint8_t devaddr, int fd) {
1124
1125         usbi_dbg("linux_initialize_device");
1126
1127         struct linux_device_priv *priv = _device_priv(dev);
1128         struct libusb_context *ctx = DEVICE_CTX(dev);
1129         uint8_t desc[4096]; // max descriptor size is 4096 bytes
1130         int speed;
1131         ssize_t r;
1132
1133         dev->bus_number = busnum;
1134         dev->device_address = devaddr;
1135
1136         usbi_dbg("cache descriptors in memory");
1137
1138         priv->descriptors_len = 0;
1139         priv->fd = 0;
1140         memset(desc, 0, sizeof(desc));
1141     if (!lseek(fd, 0, SEEK_SET)) {
1142         // ディスクリプタを読み込んでローカルキャッシュする
1143         int length = read(fd, desc, sizeof(desc));
1144         usbi_dbg("Device::init read returned %d errno %d\n", length, errno);
1145                 if (length > 0) {
1146                         priv->fd = fd;
1147                         priv->descriptors = usbi_reallocf(priv->descriptors, length);
1148                         if (!priv->descriptors) {
1149                 return (int)LIBUSB_ERROR_NO_MEM;
1150                                 //RETURN(LIBUSB_ERROR_NO_MEM, int);
1151                         }
1152                         priv->descriptors_len = length;
1153                         memcpy(priv->descriptors, desc, length);
1154                 }
1155         }
1156
1157         if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1158                 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
1159                 //LOGE("short descriptor read (%d)", priv->descriptors_len);
1160         return (int)LIBUSB_ERROR_IO;
1161                 //RETURN(LIBUSB_ERROR_IO, int);
1162         }
1163
1164         if (fd < 0) {   // if could not get fd of usbfs with read/write access
1165                 /* cannot send a control message to determine the active
1166                  * config. just assume the first one is active. */
1167                 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1168                                 "active configuration descriptor");
1169                 if (priv->descriptors_len
1170                                 >= (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1171                         struct libusb_config_descriptor config;
1172                         usbi_parse_descriptor(priv->descriptors + DEVICE_DESC_LENGTH,
1173                                 "bbwbbbbb", &config, 0);
1174                         priv->active_config = config.bConfigurationValue;
1175                 } else
1176                         priv->active_config = -1; /* No config dt */
1177
1178         return (int)LIBUSB_SUCCESS;
1179                 //RETURN(LIBUSB_SUCCESS, int);
1180         }
1181         // if we could get fd of usbfs with read/write access
1182         r = usbfs_get_active_config(dev, fd);
1183         if (r > 0) {
1184                 priv->active_config = r;
1185                 r = LIBUSB_SUCCESS;
1186         } else if (r == 0) {
1187                 /* some buggy devices have a configuration 0, but we're
1188                  * reaching into the corner of a corner case here, so let's
1189                  * not support buggy devices in these circumstances.
1190                  * stick to the specs: a configuration value of 0 means
1191                  * unconfigured. */
1192                 usbi_dbg("active cfg 0? assuming unconfigured device");
1193                 priv->active_config = -1;
1194                 r = LIBUSB_SUCCESS;
1195         } else if (r == LIBUSB_ERROR_IO) {
1196                 /* buggy devices sometimes fail to report their active config.
1197                  * assume unconfigured and continue the probing */
1198                 usbi_warn(ctx, "couldn't query active configuration, assuming"
1199                                         " unconfigured");
1200                 priv->active_config = -1;
1201                 r = LIBUSB_SUCCESS;
1202         } /* else r < 0, just return the error code */
1203
1204     return (int)r;
1205         //RETURN(r, int);
1206 }
1207
1208
1209
1210 int linux_generate_device(struct libusb_context *ctx, struct libusb_device **dev,
1211         int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
1212
1213         usbi_dbg("linux_generate_device, fd:%d, serial:%s", fd, serial);
1214         unsigned long session_id;
1215         int r = 0;
1216
1217         *dev = NULL;
1218         /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1219          * will be reused. instead we should add a simple sysfs attribute with
1220          * a session ID. */
1221         session_id = busnum << 8 | devaddr;
1222         usbi_dbg("allocating new device for %d/%d (session %ld)", busnum, devaddr, session_id);
1223         *dev = usbi_alloc_device(ctx, session_id);      // この時点で参照カウンタ=1
1224         if (!dev) {
1225         usbi_dbg("ret %d", LIBUSB_ERROR_NO_MEM);
1226         return (int)LIBUSB_ERROR_NO_MEM;
1227         }
1228
1229         r = linux_initialize_device(*dev, busnum, devaddr, fd);
1230         if (r < 0) {
1231                 usbi_err("initialize_device failed: ret=%d", r);
1232                 goto out;
1233         }
1234         r = usbi_sanitize_device(*dev);
1235         if (r < 0) {
1236             usbi_err("usbi_sanitize_device failed: ret=%d", r);
1237                 goto out;
1238         }
1239
1240 out:
1241         if (r < 0) {
1242                 libusb_unref_device(*dev);      // ここで参照カウンタが0になって破棄される
1243                 *dev = NULL;
1244         } else {
1245                 usbi_connect_device(*dev);
1246         }
1247
1248     usbi_dbg("linux_generate_device ret=%d", r);
1249     return (int)r;
1250 }
1251
1252
1253 int linux_enumerate_device(struct libusb_context *ctx,
1254         uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1255 {
1256         unsigned long session_id;
1257         struct libusb_device *dev;
1258         int r = 0;
1259
1260         /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1261          * will be reused. instead we should add a simple sysfs attribute with
1262          * a session ID. */
1263         session_id = busnum << 8 | devaddr;
1264         usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1265                 session_id);
1266
1267         dev = usbi_get_device_by_session_id(ctx, session_id);
1268         if (dev) {
1269                 /* device already exists in the context */
1270                 usbi_dbg("session_id %ld already exists", session_id);
1271                 libusb_unref_device(dev);
1272                 return LIBUSB_SUCCESS;
1273         }
1274
1275         usbi_dbg("allocating new device for %d/%d (session %ld)",
1276                  busnum, devaddr, session_id);
1277         dev = usbi_alloc_device(ctx, session_id);
1278         if (!dev)
1279                 return LIBUSB_ERROR_NO_MEM;
1280
1281         r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1282         if (r < 0)
1283                 goto out;
1284         r = usbi_sanitize_device(dev);
1285         if (r < 0)
1286                 goto out;
1287
1288         r = linux_get_parent_info(dev, sysfs_dir);
1289         if (r < 0)
1290                 goto out;
1291 out:
1292         if (r < 0)
1293                 libusb_unref_device(dev);
1294         else
1295                 usbi_connect_device(dev);
1296
1297         return r;
1298 }
1299
1300 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1301 {
1302         struct libusb_context *ctx;
1303
1304         usbi_mutex_static_lock(&active_contexts_lock);
1305         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1306                 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1307         }
1308         usbi_mutex_static_unlock(&active_contexts_lock);
1309 }
1310
1311 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1312 {
1313         struct libusb_context *ctx;
1314         struct libusb_device *dev;
1315         unsigned long session_id = busnum << 8 | devaddr;
1316
1317         usbi_mutex_static_lock(&active_contexts_lock);
1318         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1319                 dev = usbi_get_device_by_session_id (ctx, session_id);
1320                 if (NULL != dev) {
1321                         usbi_disconnect_device (dev);
1322                         libusb_unref_device(dev);
1323                 } else {
1324                         usbi_dbg("device not found for session %x", session_id);
1325                 }
1326         }
1327         usbi_mutex_static_unlock(&active_contexts_lock);
1328 }
1329
1330 #if !defined(USE_UDEV)
1331 /* open a bus directory and adds all discovered devices to the context */
1332 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1333 {
1334         DIR *dir;
1335         char dirpath[PATH_MAX];
1336         struct dirent *entry;
1337         int r = LIBUSB_ERROR_IO;
1338
1339         snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1340         usbi_dbg("%s", dirpath);
1341         dir = opendir(dirpath);
1342         if (!dir) {
1343                 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1344                 /* FIXME: should handle valid race conditions like hub unplugged
1345                  * during directory iteration - this is not an error */
1346                 return r;
1347         }
1348
1349         while ((entry = readdir(dir))) {
1350                 int devaddr;
1351
1352                 if (entry->d_name[0] == '.')
1353                         continue;
1354
1355                 devaddr = atoi(entry->d_name);
1356                 if (devaddr == 0) {
1357                         usbi_dbg("unknown dir entry %s", entry->d_name);
1358                         continue;
1359                 }
1360
1361                 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1362                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1363                         continue;
1364                 }
1365
1366                 r = 0;
1367         }
1368
1369         closedir(dir);
1370         return r;
1371 }
1372
1373 static int usbfs_get_device_list(struct libusb_context *ctx)
1374 {
1375         struct dirent *entry;
1376         DIR *buses = opendir(usbfs_path);
1377         int r = 0;
1378
1379         if (!buses) {
1380                 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1381                 return LIBUSB_ERROR_IO;
1382         }
1383
1384         while ((entry = readdir(buses))) {
1385                 int busnum;
1386
1387                 if (entry->d_name[0] == '.')
1388                         continue;
1389
1390                 if (usbdev_names) {
1391                         int devaddr;
1392                         if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1393                                 continue;
1394
1395                         r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1396                         if (r < 0) {
1397                                 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1398                                 continue;
1399                         }
1400                 } else {
1401                         busnum = atoi(entry->d_name);
1402                         if (busnum == 0) {
1403                                 usbi_dbg("unknown dir entry %s", entry->d_name);
1404                                 continue;
1405                         }
1406
1407                         r = usbfs_scan_busdir(ctx, busnum);
1408                         if (r < 0)
1409                                 break;
1410                 }
1411         }
1412
1413         closedir(buses);
1414         return r;
1415
1416 }
1417 #endif
1418
1419 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1420 {
1421         uint8_t busnum, devaddr;
1422         int ret;
1423
1424         ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1425         if (LIBUSB_SUCCESS != ret) {
1426                 return ret;
1427         }
1428
1429         return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1430                 devname);
1431 }
1432
1433 #if !defined(USE_UDEV)
1434 static int sysfs_get_device_list(struct libusb_context *ctx)
1435 {
1436         DIR *devices = opendir(SYSFS_DEVICE_PATH);
1437         struct dirent *entry;
1438         int num_devices = 0;
1439         int num_enumerated = 0;
1440
1441         if (!devices) {
1442                 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1443                 return LIBUSB_ERROR_IO;
1444         }
1445
1446         while ((entry = readdir(devices))) {
1447                 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1448                                 || strchr(entry->d_name, ':'))
1449                         continue;
1450
1451                 num_devices++;
1452
1453                 if (sysfs_scan_device(ctx, entry->d_name)) {
1454                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1455                         continue;
1456                 }
1457
1458                 num_enumerated++;
1459         }
1460
1461         closedir(devices);
1462
1463         /* successful if at least one device was enumerated or no devices were found */
1464         if (num_enumerated || !num_devices)
1465                 return LIBUSB_SUCCESS;
1466         else
1467                 return LIBUSB_ERROR_IO;
1468 }
1469
1470 static int linux_default_scan_devices (struct libusb_context *ctx)
1471 {
1472         /* we can retrieve device list and descriptors from sysfs or usbfs.
1473          * sysfs is preferable, because if we use usbfs we end up resuming
1474          * any autosuspended USB devices. however, sysfs is not available
1475          * everywhere, so we need a usbfs fallback too.
1476          *
1477          * as described in the "sysfs vs usbfs" comment at the top of this
1478          * file, sometimes we have sysfs but not enough information to
1479          * relate sysfs devices to usbfs nodes.  op_init() determines the
1480          * adequacy of sysfs and sets sysfs_can_relate_devices.
1481          */
1482         if (sysfs_can_relate_devices != 0)
1483                 return sysfs_get_device_list(ctx);
1484         else
1485                 return usbfs_get_device_list(ctx);
1486 }
1487 #endif
1488
1489 static int op_open(struct libusb_device_handle *handle)
1490 {
1491         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1492         int r;
1493
1494         hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1495         if (hpriv->fd < 0) {
1496                 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1497                         /* device will still be marked as attached if hotplug monitor thread
1498                          * hasn't processed remove event yet */
1499                         usbi_mutex_static_lock(&linux_hotplug_lock);
1500                         if (handle->dev->attached) {
1501                                 usbi_dbg("open failed with no device, but device still attached");
1502                                 linux_device_disconnected(handle->dev->bus_number,
1503                                                 handle->dev->device_address);
1504                         }
1505                         usbi_mutex_static_unlock(&linux_hotplug_lock);
1506                 }
1507                 return hpriv->fd;
1508         }
1509
1510         r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1511         if (r < 0) {
1512                 if (errno == ENOTTY)
1513                         usbi_dbg("getcap not available");
1514                 else
1515                         usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1516                 hpriv->caps = 0;
1517                 if (supports_flag_zero_packet)
1518                         hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1519                 if (supports_flag_bulk_continuation)
1520                         hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1521         }
1522
1523         r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1524         if (r < 0)
1525                 close(hpriv->fd);
1526
1527         return r;
1528 }
1529
1530 static void op_close(struct libusb_device_handle *dev_handle)
1531 {
1532         struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1533         /* fd may have already been removed by POLLERR condition in op_handle_events() */
1534         if (!hpriv->fd_removed)
1535                 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1536         close(hpriv->fd);
1537 }
1538
1539 static int op_get_configuration(struct libusb_device_handle *handle,
1540         int *config)
1541 {
1542         int r;
1543
1544         if (sysfs_can_relate_devices) {
1545                 r = sysfs_get_active_config(handle->dev, config);
1546         } else {
1547                 r = usbfs_get_active_config(handle->dev,
1548                                             _device_handle_priv(handle)->fd);
1549                 if (r == LIBUSB_SUCCESS)
1550                         *config = _device_priv(handle->dev)->active_config;
1551         }
1552         if (r < 0)
1553                 return r;
1554
1555         if (*config == -1) {
1556                 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1557                 *config = 0;
1558         }
1559
1560         return 0;
1561 }
1562
1563 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1564 {
1565         struct linux_device_priv *priv = _device_priv(handle->dev);
1566         int fd = _device_handle_priv(handle)->fd;
1567         int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1568         if (r) {
1569                 if (errno == EINVAL)
1570                         return LIBUSB_ERROR_NOT_FOUND;
1571                 else if (errno == EBUSY)
1572                         return LIBUSB_ERROR_BUSY;
1573                 else if (errno == ENODEV)
1574                         return LIBUSB_ERROR_NO_DEVICE;
1575
1576                 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1577                 return LIBUSB_ERROR_OTHER;
1578         }
1579
1580         /* update our cached active config descriptor */
1581         priv->active_config = config;
1582
1583         return LIBUSB_SUCCESS;
1584 }
1585
1586 static int claim_interface(struct libusb_device_handle *handle, int iface)
1587 {
1588         int fd = _device_handle_priv(handle)->fd;
1589         int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1590         if (r) {
1591                 if (errno == ENOENT)
1592                         return LIBUSB_ERROR_NOT_FOUND;
1593                 else if (errno == EBUSY)
1594                         return LIBUSB_ERROR_BUSY;
1595                 else if (errno == ENODEV)
1596                         return LIBUSB_ERROR_NO_DEVICE;
1597
1598                 usbi_err(HANDLE_CTX(handle),
1599                         "claim interface failed, error %d errno %d", r, errno);
1600                 return LIBUSB_ERROR_OTHER;
1601         }
1602         return 0;
1603 }
1604
1605 static int release_interface(struct libusb_device_handle *handle, int iface)
1606 {
1607         int fd = _device_handle_priv(handle)->fd;
1608         int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1609         if (r) {
1610                 if (errno == ENODEV)
1611                         return LIBUSB_ERROR_NO_DEVICE;
1612
1613                 usbi_err(HANDLE_CTX(handle),
1614                         "release interface failed, error %d errno %d", r, errno);
1615                 return LIBUSB_ERROR_OTHER;
1616         }
1617         return 0;
1618 }
1619
1620 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1621         int altsetting)
1622 {
1623         int fd = _device_handle_priv(handle)->fd;
1624         struct usbfs_setinterface setintf;
1625         int r;
1626
1627         setintf.interface = iface;
1628         setintf.altsetting = altsetting;
1629         r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1630         if (r) {
1631                 if (errno == EINVAL)
1632                         return LIBUSB_ERROR_NOT_FOUND;
1633                 else if (errno == ENODEV)
1634                         return LIBUSB_ERROR_NO_DEVICE;
1635
1636                 usbi_err(HANDLE_CTX(handle),
1637                         "setintf failed error %d errno %d", r, errno);
1638                 return LIBUSB_ERROR_OTHER;
1639         }
1640
1641         return 0;
1642 }
1643
1644 static int op_clear_halt(struct libusb_device_handle *handle,
1645         unsigned char endpoint)
1646 {
1647         int fd = _device_handle_priv(handle)->fd;
1648         unsigned int _endpoint = endpoint;
1649         int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1650         if (r) {
1651                 if (errno == ENOENT)
1652                         return LIBUSB_ERROR_NOT_FOUND;
1653                 else if (errno == ENODEV)
1654                         return LIBUSB_ERROR_NO_DEVICE;
1655
1656                 usbi_err(HANDLE_CTX(handle),
1657                         "clear_halt failed error %d errno %d", r, errno);
1658                 return LIBUSB_ERROR_OTHER;
1659         }
1660
1661         return 0;
1662 }
1663
1664 static int op_reset_device(struct libusb_device_handle *handle)
1665 {
1666         int fd = _device_handle_priv(handle)->fd;
1667         int i, r, ret = 0;
1668
1669         /* Doing a device reset will cause the usbfs driver to get unbound
1670            from any interfaces it is bound to. By voluntarily unbinding
1671            the usbfs driver ourself, we stop the kernel from rebinding
1672            the interface after reset (which would end up with the interface
1673            getting bound to the in kernel driver if any). */
1674         for (i = 0; i < USB_MAXINTERFACES; i++) {
1675                 if (handle->claimed_interfaces & (1L << i)) {
1676                         release_interface(handle, i);
1677                 }
1678         }
1679
1680         usbi_mutex_lock(&handle->lock);
1681         r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1682         if (r) {
1683                 if (errno == ENODEV) {
1684                         ret = LIBUSB_ERROR_NOT_FOUND;
1685                         goto out;
1686                 }
1687
1688                 usbi_err(HANDLE_CTX(handle),
1689                         "reset failed error %d errno %d", r, errno);
1690                 ret = LIBUSB_ERROR_OTHER;
1691                 goto out;
1692         }
1693
1694         /* And re-claim any interfaces which were claimed before the reset */
1695         for (i = 0; i < USB_MAXINTERFACES; i++) {
1696                 if (handle->claimed_interfaces & (1L << i)) {
1697                         /*
1698                          * A driver may have completed modprobing during
1699                          * IOCTL_USBFS_RESET, and bound itself as soon as
1700                          * IOCTL_USBFS_RESET released the device lock
1701                          */
1702                         r = detach_kernel_driver_and_claim(handle, i);
1703                         if (r) {
1704                                 usbi_warn(HANDLE_CTX(handle),
1705                                         "failed to re-claim interface %d after reset: %s",
1706                                         i, libusb_error_name(r));
1707                                 handle->claimed_interfaces &= ~(1L << i);
1708                                 ret = LIBUSB_ERROR_NOT_FOUND;
1709                         }
1710                 }
1711         }
1712 out:
1713         usbi_mutex_unlock(&handle->lock);
1714         return ret;
1715 }
1716
1717 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1718         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1719 {
1720         int r, fd = _device_handle_priv(handle)->fd;
1721         struct usbfs_streams *streams;
1722
1723         if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1724                 return LIBUSB_ERROR_INVALID_PARAM;
1725
1726         streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1727         if (!streams)
1728                 return LIBUSB_ERROR_NO_MEM;
1729
1730         streams->num_streams = num_streams;
1731         streams->num_eps = num_endpoints;
1732         memcpy(streams->eps, endpoints, num_endpoints);
1733
1734         r = ioctl(fd, req, streams);
1735
1736         free(streams);
1737
1738         if (r < 0) {
1739                 if (errno == ENOTTY)
1740                         return LIBUSB_ERROR_NOT_SUPPORTED;
1741                 else if (errno == EINVAL)
1742                         return LIBUSB_ERROR_INVALID_PARAM;
1743                 else if (errno == ENODEV)
1744                         return LIBUSB_ERROR_NO_DEVICE;
1745
1746                 usbi_err(HANDLE_CTX(handle),
1747                         "streams-ioctl failed error %d errno %d", r, errno);
1748                 return LIBUSB_ERROR_OTHER;
1749         }
1750         return r;
1751 }
1752
1753 static int op_alloc_streams(struct libusb_device_handle *handle,
1754         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1755 {
1756         return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1757                                 num_streams, endpoints, num_endpoints);
1758 }
1759
1760 static int op_free_streams(struct libusb_device_handle *handle,
1761                 unsigned char *endpoints, int num_endpoints)
1762 {
1763         return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1764                                 endpoints, num_endpoints);
1765 }
1766
1767 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1768         size_t len)
1769 {
1770         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1771         unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1772                 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1773         if (buffer == MAP_FAILED) {
1774                 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1775                         errno);
1776                 return NULL;
1777         }
1778         return buffer;
1779 }
1780
1781 static int op_dev_mem_free(struct libusb_device_handle *handle,
1782         unsigned char *buffer, size_t len)
1783 {
1784         if (munmap(buffer, len) != 0) {
1785                 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1786                         errno);
1787                 return LIBUSB_ERROR_OTHER;
1788         } else {
1789                 return LIBUSB_SUCCESS;
1790         }
1791 }
1792
1793 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1794         int interface)
1795 {
1796         int fd = _device_handle_priv(handle)->fd;
1797         struct usbfs_getdriver getdrv;
1798         int r;
1799
1800         getdrv.interface = interface;
1801         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1802         if (r) {
1803                 if (errno == ENODATA)
1804                         return 0;
1805                 else if (errno == ENODEV)
1806                         return LIBUSB_ERROR_NO_DEVICE;
1807
1808                 usbi_err(HANDLE_CTX(handle),
1809                         "get driver failed error %d errno %d", r, errno);
1810                 return LIBUSB_ERROR_OTHER;
1811         }
1812
1813         return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1814 }
1815
1816 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1817         int interface)
1818 {
1819         int fd = _device_handle_priv(handle)->fd;
1820         struct usbfs_ioctl command;
1821         struct usbfs_getdriver getdrv;
1822         int r;
1823
1824         command.ifno = interface;
1825         command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1826         command.data = NULL;
1827
1828         getdrv.interface = interface;
1829         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1830         if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1831                 return LIBUSB_ERROR_NOT_FOUND;
1832
1833         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1834         if (r) {
1835                 if (errno == ENODATA)
1836                         return LIBUSB_ERROR_NOT_FOUND;
1837                 else if (errno == EINVAL)
1838                         return LIBUSB_ERROR_INVALID_PARAM;
1839                 else if (errno == ENODEV)
1840                         return LIBUSB_ERROR_NO_DEVICE;
1841
1842                 usbi_err(HANDLE_CTX(handle),
1843                         "detach failed error %d errno %d", r, errno);
1844                 return LIBUSB_ERROR_OTHER;
1845         }
1846
1847         return 0;
1848 }
1849
1850 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1851         int interface)
1852 {
1853         int fd = _device_handle_priv(handle)->fd;
1854         struct usbfs_ioctl command;
1855         int r;
1856
1857         command.ifno = interface;
1858         command.ioctl_code = IOCTL_USBFS_CONNECT;
1859         command.data = NULL;
1860
1861         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1862         if (r < 0) {
1863                 if (errno == ENODATA)
1864                         return LIBUSB_ERROR_NOT_FOUND;
1865                 else if (errno == EINVAL)
1866                         return LIBUSB_ERROR_INVALID_PARAM;
1867                 else if (errno == ENODEV)
1868                         return LIBUSB_ERROR_NO_DEVICE;
1869                 else if (errno == EBUSY)
1870                         return LIBUSB_ERROR_BUSY;
1871
1872                 usbi_err(HANDLE_CTX(handle),
1873                         "attach failed error %d errno %d", r, errno);
1874                 return LIBUSB_ERROR_OTHER;
1875         } else if (r == 0) {
1876                 return LIBUSB_ERROR_NOT_FOUND;
1877         }
1878
1879         return 0;
1880 }
1881
1882 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1883         int interface)
1884 {
1885         struct usbfs_disconnect_claim dc;
1886         int r, fd = _device_handle_priv(handle)->fd;
1887
1888         dc.interface = interface;
1889         strcpy(dc.driver, "usbfs");
1890         dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1891         r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1892         if (r != 0 && errno != ENOTTY) {
1893                 switch (errno) {
1894                 case EBUSY:
1895                         return LIBUSB_ERROR_BUSY;
1896                 case EINVAL:
1897                         return LIBUSB_ERROR_INVALID_PARAM;
1898                 case ENODEV:
1899                         return LIBUSB_ERROR_NO_DEVICE;
1900                 }
1901                 usbi_err(HANDLE_CTX(handle),
1902                         "disconnect-and-claim failed errno %d", errno);
1903                 return LIBUSB_ERROR_OTHER;
1904         } else if (r == 0)
1905                 return 0;
1906
1907         /* Fallback code for kernels which don't support the
1908            disconnect-and-claim ioctl */
1909         r = op_detach_kernel_driver(handle, interface);
1910         if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1911                 return r;
1912
1913         return claim_interface(handle, interface);
1914 }
1915
1916 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1917 {
1918         if (handle->auto_detach_kernel_driver)
1919                 return detach_kernel_driver_and_claim(handle, iface);
1920         else
1921                 return claim_interface(handle, iface);
1922 }
1923
1924 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1925 {
1926         int r;
1927
1928         r = release_interface(handle, iface);
1929         if (r)
1930                 return r;
1931
1932         if (handle->auto_detach_kernel_driver)
1933                 op_attach_kernel_driver(handle, iface);
1934
1935         return 0;
1936 }
1937
1938 static void op_destroy_device(struct libusb_device *dev)
1939 {
1940         struct linux_device_priv *priv = _device_priv(dev);
1941         if (priv->descriptors)
1942                 free(priv->descriptors);
1943         if (priv->sysfs_dir)
1944                 free(priv->sysfs_dir);
1945 }
1946
1947 /* URBs are discarded in reverse order of submission to avoid races. */
1948 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1949 {
1950         struct libusb_transfer *transfer =
1951                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1952         struct linux_transfer_priv *tpriv =
1953                 usbi_transfer_get_os_priv(itransfer);
1954         struct linux_device_handle_priv *dpriv =
1955                 _device_handle_priv(transfer->dev_handle);
1956         int i, ret = 0;
1957         struct usbfs_urb *urb;
1958
1959         for (i = last_plus_one - 1; i >= first; i--) {
1960                 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1961                         urb = tpriv->iso_urbs[i];
1962                 else
1963                         urb = &tpriv->urbs[i];
1964
1965                 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1966                         continue;
1967
1968                 if (EINVAL == errno) {
1969                         usbi_dbg("URB not found --> assuming ready to be reaped");
1970                         if (i == (last_plus_one - 1))
1971                                 ret = LIBUSB_ERROR_NOT_FOUND;
1972                 } else if (ENODEV == errno) {
1973                         usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1974                         ret = LIBUSB_ERROR_NO_DEVICE;
1975                 } else {
1976                         usbi_warn(TRANSFER_CTX(transfer),
1977                                 "unrecognised discard errno %d", errno);
1978                         ret = LIBUSB_ERROR_OTHER;
1979                 }
1980         }
1981         return ret;
1982 }
1983
1984 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1985 {
1986         int i;
1987         for (i = 0; i < tpriv->num_urbs; i++) {
1988                 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1989                 if (!urb)
1990                         break;
1991                 free(urb);
1992         }
1993
1994         free(tpriv->iso_urbs);
1995         tpriv->iso_urbs = NULL;
1996 }
1997
1998 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1999 {
2000         struct libusb_transfer *transfer =
2001                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2002         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2003         struct linux_device_handle_priv *dpriv =
2004                 _device_handle_priv(transfer->dev_handle);
2005         struct usbfs_urb *urbs;
2006         int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
2007                 == LIBUSB_ENDPOINT_OUT;
2008         int bulk_buffer_len, use_bulk_continuation;
2009         int r;
2010         int i;
2011
2012         if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
2013                         !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
2014                 return LIBUSB_ERROR_NOT_SUPPORTED;
2015
2016         /*
2017          * Older versions of usbfs place a 16kb limit on bulk URBs. We work
2018          * around this by splitting large transfers into 16k blocks, and then
2019          * submit all urbs at once. it would be simpler to submit one urb at
2020          * a time, but there is a big performance gain doing it this way.
2021          *
2022          * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
2023          * using arbritary large transfers can still be a bad idea though, as
2024          * the kernel needs to allocate physical contiguous memory for this,
2025          * which may fail for large buffers.
2026          *
2027          * The kernel solves this problem by splitting the transfer into
2028          * blocks itself when the host-controller is scatter-gather capable
2029          * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
2030          *
2031          * Last, there is the issue of short-transfers when splitting, for
2032          * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
2033          * is needed, but this is not always available.
2034          */
2035         if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
2036                 /* Good! Just submit everything in one go */
2037                 bulk_buffer_len = transfer->length ? transfer->length : 1;
2038                 use_bulk_continuation = 0;
2039         } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
2040                 /* Split the transfers and use bulk-continuation to
2041                    avoid issues with short-transfers */
2042                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2043                 use_bulk_continuation = 1;
2044         } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
2045                 /* Don't split, assume the kernel can alloc the buffer
2046                    (otherwise the submit will fail with -ENOMEM) */
2047                 bulk_buffer_len = transfer->length ? transfer->length : 1;
2048                 use_bulk_continuation = 0;
2049         } else {
2050                 /* Bad, splitting without bulk-continuation, short transfers
2051                    which end before the last urb will not work reliable! */
2052                 /* Note we don't warn here as this is "normal" on kernels <
2053                    2.6.32 and not a problem for most applications */
2054                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
2055                 use_bulk_continuation = 0;
2056         }
2057
2058         int num_urbs = transfer->length / bulk_buffer_len;
2059         int last_urb_partial = 0;
2060
2061         if (transfer->length == 0) {
2062                 num_urbs = 1;
2063         } else if ((transfer->length % bulk_buffer_len) > 0) {
2064                 last_urb_partial = 1;
2065                 num_urbs++;
2066         }
2067         usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2068                 transfer->length);
2069         urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
2070         if (!urbs)
2071                 return LIBUSB_ERROR_NO_MEM;
2072         tpriv->urbs = urbs;
2073         tpriv->num_urbs = num_urbs;
2074         tpriv->num_retired = 0;
2075         tpriv->reap_action = NORMAL;
2076         tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
2077
2078         for (i = 0; i < num_urbs; i++) {
2079                 struct usbfs_urb *urb = &urbs[i];
2080                 urb->usercontext = itransfer;
2081                 switch (transfer->type) {
2082                 case LIBUSB_TRANSFER_TYPE_BULK:
2083                         urb->type = USBFS_URB_TYPE_BULK;
2084                         urb->stream_id = 0;
2085                         break;
2086                 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2087                         urb->type = USBFS_URB_TYPE_BULK;
2088                         urb->stream_id = itransfer->stream_id;
2089                         break;
2090                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2091                         urb->type = USBFS_URB_TYPE_INTERRUPT;
2092                         break;
2093                 }
2094                 urb->endpoint = transfer->endpoint;
2095                 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2096                 /* don't set the short not ok flag for the last URB */
2097                 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2098                         urb->flags = USBFS_URB_SHORT_NOT_OK;
2099                 if (i == num_urbs - 1 && last_urb_partial)
2100                         urb->buffer_length = transfer->length % bulk_buffer_len;
2101                 else if (transfer->length == 0)
2102                         urb->buffer_length = 0;
2103                 else
2104                         urb->buffer_length = bulk_buffer_len;
2105
2106                 if (i > 0 && use_bulk_continuation)
2107                         urb->flags |= USBFS_URB_BULK_CONTINUATION;
2108
2109                 /* we have already checked that the flag is supported */
2110                 if (is_out && i == num_urbs - 1 &&
2111                     transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2112                         urb->flags |= USBFS_URB_ZERO_PACKET;
2113
2114                 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2115                 if (r < 0) {
2116                         if (errno == ENODEV) {
2117                                 r = LIBUSB_ERROR_NO_DEVICE;
2118                         } else {
2119                                 usbi_err(TRANSFER_CTX(transfer),
2120                                         "submiturb failed error %d errno=%d", r, errno);
2121                                 r = LIBUSB_ERROR_IO;
2122                         }
2123
2124                         /* if the first URB submission fails, we can simply free up and
2125                          * return failure immediately. */
2126                         if (i == 0) {
2127                                 usbi_dbg("first URB failed, easy peasy");
2128                                 free(urbs);
2129                                 tpriv->urbs = NULL;
2130                                 return r;
2131                         }
2132
2133                         /* if it's not the first URB that failed, the situation is a bit
2134                          * tricky. we may need to discard all previous URBs. there are
2135                          * complications:
2136                          *  - discarding is asynchronous - discarded urbs will be reaped
2137                          *    later. the user must not have freed the transfer when the
2138                          *    discarded URBs are reaped, otherwise libusb will be using
2139                          *    freed memory.
2140                          *  - the earlier URBs may have completed successfully and we do
2141                          *    not want to throw away any data.
2142                          *  - this URB failing may be no error; EREMOTEIO means that
2143                          *    this transfer simply didn't need all the URBs we submitted
2144                          * so, we report that the transfer was submitted successfully and
2145                          * in case of error we discard all previous URBs. later when
2146                          * the final reap completes we can report error to the user,
2147                          * or success if an earlier URB was completed successfully.
2148                          */
2149                         tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2150
2151                         /* The URBs we haven't submitted yet we count as already
2152                          * retired. */
2153                         tpriv->num_retired += num_urbs - i;
2154
2155                         /* If we completed short then don't try to discard. */
2156                         if (COMPLETED_EARLY == tpriv->reap_action)
2157                                 return 0;
2158
2159                         discard_urbs(itransfer, 0, i);
2160
2161                         usbi_dbg("reporting successful submission but waiting for %d "
2162                                 "discards before reporting error", i);
2163                         return 0;
2164                 }
2165         }
2166
2167         return 0;
2168 }
2169
2170 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2171 {
2172         struct libusb_transfer *transfer =
2173                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2174         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2175         struct linux_device_handle_priv *dpriv =
2176                 _device_handle_priv(transfer->dev_handle);
2177         struct usbfs_urb **urbs;
2178         int num_packets = transfer->num_iso_packets;
2179         int num_packets_remaining;
2180         int i, j;
2181         int num_urbs;
2182         unsigned int packet_len;
2183         unsigned int total_len = 0;
2184         unsigned char *urb_buffer = transfer->buffer;
2185
2186         if (num_packets < 1)
2187                 return LIBUSB_ERROR_INVALID_PARAM;
2188
2189         /* usbfs places arbitrary limits on iso URBs. this limit has changed
2190          * at least three times, but we attempt to detect this limit during
2191          * init and check it here. if the kernel rejects the request due to
2192          * its size, we return an error indicating such to the user.
2193          */
2194         for (i = 0; i < num_packets; i++) {
2195                 packet_len = transfer->iso_packet_desc[i].length;
2196
2197                 if (packet_len > max_iso_packet_len) {
2198                         usbi_warn(TRANSFER_CTX(transfer),
2199                                 "iso packet length of %u bytes exceeds maximum of %u bytes",
2200                                 packet_len, max_iso_packet_len);
2201                         return LIBUSB_ERROR_INVALID_PARAM;
2202                 }
2203
2204                 total_len += packet_len;
2205         }
2206
2207         if (transfer->length < (int)total_len)
2208                 return LIBUSB_ERROR_INVALID_PARAM;
2209
2210         /* usbfs limits the number of iso packets per URB */
2211         num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2212
2213         usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
2214                 transfer->length);
2215
2216         urbs = calloc(num_urbs, sizeof(*urbs));
2217         if (!urbs)
2218                 return LIBUSB_ERROR_NO_MEM;
2219
2220         tpriv->iso_urbs = urbs;
2221         tpriv->num_urbs = num_urbs;
2222         tpriv->num_retired = 0;
2223         tpriv->reap_action = NORMAL;
2224         tpriv->iso_packet_offset = 0;
2225
2226         /* allocate + initialize each URB with the correct number of packets */
2227         num_packets_remaining = num_packets;
2228         for (i = 0, j = 0; i < num_urbs; i++) {
2229                 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2230                 struct usbfs_urb *urb;
2231                 size_t alloc_size;
2232                 int k;
2233
2234                 alloc_size = sizeof(*urb)
2235                         + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2236                 urb = calloc(1, alloc_size);
2237                 if (!urb) {
2238                         free_iso_urbs(tpriv);
2239                         return LIBUSB_ERROR_NO_MEM;
2240                 }
2241                 urbs[i] = urb;
2242
2243                 /* populate packet lengths */
2244                 for (k = 0; k < num_packets_in_urb; j++, k++) {
2245                         packet_len = transfer->iso_packet_desc[j].length;
2246                         urb->buffer_length += packet_len;
2247                         urb->iso_frame_desc[k].length = packet_len;
2248                 }
2249
2250                 urb->usercontext = itransfer;
2251                 urb->type = USBFS_URB_TYPE_ISO;
2252                 /* FIXME: interface for non-ASAP data? */
2253                 urb->flags = USBFS_URB_ISO_ASAP;
2254                 urb->endpoint = transfer->endpoint;
2255                 urb->number_of_packets = num_packets_in_urb;
2256                 urb->buffer = urb_buffer;
2257
2258                 urb_buffer += urb->buffer_length;
2259                 num_packets_remaining -= num_packets_in_urb;
2260         }
2261
2262         /* submit URBs */
2263         for (i = 0; i < num_urbs; i++) {
2264                 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2265                 if (r < 0) {
2266                         if (errno == ENODEV) {
2267                                 r = LIBUSB_ERROR_NO_DEVICE;
2268                         } else if (errno == EINVAL) {
2269                                 usbi_warn(TRANSFER_CTX(transfer),
2270                                         "submiturb failed, transfer too large");
2271                                 r = LIBUSB_ERROR_INVALID_PARAM;
2272                         } else if (errno == EMSGSIZE) {
2273                                 usbi_warn(TRANSFER_CTX(transfer),
2274                                         "submiturb failed, iso packet length too large");
2275                                 r = LIBUSB_ERROR_INVALID_PARAM;
2276                         } else {
2277                                 usbi_err(TRANSFER_CTX(transfer),
2278                                         "submiturb failed error %d errno=%d", r, errno);
2279                                 r = LIBUSB_ERROR_IO;
2280                         }
2281
2282                         /* if the first URB submission fails, we can simply free up and
2283                          * return failure immediately. */
2284                         if (i == 0) {
2285                                 usbi_dbg("first URB failed, easy peasy");
2286                                 free_iso_urbs(tpriv);
2287                                 return r;
2288                         }
2289
2290                         /* if it's not the first URB that failed, the situation is a bit
2291                          * tricky. we must discard all previous URBs. there are
2292                          * complications:
2293                          *  - discarding is asynchronous - discarded urbs will be reaped
2294                          *    later. the user must not have freed the transfer when the
2295                          *    discarded URBs are reaped, otherwise libusb will be using
2296                          *    freed memory.
2297                          *  - the earlier URBs may have completed successfully and we do
2298                          *    not want to throw away any data.
2299                          * so, in this case we discard all the previous URBs BUT we report
2300                          * that the transfer was submitted successfully. then later when
2301                          * the final discard completes we can report error to the user.
2302                          */
2303                         tpriv->reap_action = SUBMIT_FAILED;
2304
2305                         /* The URBs we haven't submitted yet we count as already
2306                          * retired. */
2307                         tpriv->num_retired = num_urbs - i;
2308                         discard_urbs(itransfer, 0, i);
2309
2310                         usbi_dbg("reporting successful submission but waiting for %d "
2311                                 "discards before reporting error", i);
2312                         return 0;
2313                 }
2314         }
2315
2316         return 0;
2317 }
2318
2319 static int submit_control_transfer(struct usbi_transfer *itransfer)
2320 {
2321         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2322         struct libusb_transfer *transfer =
2323                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2324         struct linux_device_handle_priv *dpriv =
2325                 _device_handle_priv(transfer->dev_handle);
2326         struct usbfs_urb *urb;
2327         int r;
2328
2329         if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2330                 return LIBUSB_ERROR_INVALID_PARAM;
2331
2332         urb = calloc(1, sizeof(struct usbfs_urb));
2333         if (!urb)
2334                 return LIBUSB_ERROR_NO_MEM;
2335         tpriv->urbs = urb;
2336         tpriv->num_urbs = 1;
2337         tpriv->reap_action = NORMAL;
2338
2339         urb->usercontext = itransfer;
2340         urb->type = USBFS_URB_TYPE_CONTROL;
2341         urb->endpoint = transfer->endpoint;
2342         urb->buffer = transfer->buffer;
2343         urb->buffer_length = transfer->length;
2344
2345         r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2346         if (r < 0) {
2347                 free(urb);
2348                 tpriv->urbs = NULL;
2349                 if (errno == ENODEV)
2350                         return LIBUSB_ERROR_NO_DEVICE;
2351
2352                 usbi_err(TRANSFER_CTX(transfer),
2353                         "submiturb failed error %d errno=%d", r, errno);
2354                 return LIBUSB_ERROR_IO;
2355         }
2356         return 0;
2357 }
2358
2359 static int op_submit_transfer(struct usbi_transfer *itransfer)
2360 {
2361         struct libusb_transfer *transfer =
2362                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2363
2364         switch (transfer->type) {
2365         case LIBUSB_TRANSFER_TYPE_CONTROL:
2366                 return submit_control_transfer(itransfer);
2367         case LIBUSB_TRANSFER_TYPE_BULK:
2368         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2369                 return submit_bulk_transfer(itransfer);
2370         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2371                 return submit_bulk_transfer(itransfer);
2372         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2373                 return submit_iso_transfer(itransfer);
2374         default:
2375                 usbi_err(TRANSFER_CTX(transfer),
2376                         "unknown endpoint type %d", transfer->type);
2377                 return LIBUSB_ERROR_INVALID_PARAM;
2378         }
2379 }
2380
2381 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2382 {
2383         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2384         struct libusb_transfer *transfer =
2385                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2386         int r;
2387
2388         if (!tpriv->urbs)
2389                 return LIBUSB_ERROR_NOT_FOUND;
2390
2391         r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2392         if (r != 0)
2393                 return r;
2394
2395         switch (transfer->type) {
2396         case LIBUSB_TRANSFER_TYPE_BULK:
2397         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2398                 if (tpriv->reap_action == ERROR)
2399                         break;
2400                 /* else, fall through */
2401         default:
2402                 tpriv->reap_action = CANCELLED;
2403         }
2404
2405         return 0;
2406 }
2407
2408 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2409 {
2410         struct libusb_transfer *transfer =
2411                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2412         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2413
2414         switch (transfer->type) {
2415         case LIBUSB_TRANSFER_TYPE_CONTROL:
2416         case LIBUSB_TRANSFER_TYPE_BULK:
2417         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2418         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2419                 if (tpriv->urbs) {
2420                         free(tpriv->urbs);
2421                         tpriv->urbs = NULL;
2422                 }
2423                 break;
2424         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2425                 if (tpriv->iso_urbs) {
2426                         free_iso_urbs(tpriv);
2427                         tpriv->iso_urbs = NULL;
2428                 }
2429                 break;
2430         default:
2431                 usbi_err(TRANSFER_CTX(transfer),
2432                         "unknown endpoint type %d", transfer->type);
2433         }
2434 }
2435
2436 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2437         struct usbfs_urb *urb)
2438 {
2439         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2440         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2441         int urb_idx = urb - tpriv->urbs;
2442
2443         usbi_mutex_lock(&itransfer->lock);
2444         usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2445                 urb_idx + 1, tpriv->num_urbs);
2446
2447         tpriv->num_retired++;
2448
2449         if (tpriv->reap_action != NORMAL) {
2450                 /* cancelled, submit_fail, or completed early */
2451                 usbi_dbg("abnormal reap: urb status %d", urb->status);
2452
2453                 /* even though we're in the process of cancelling, it's possible that
2454                  * we may receive some data in these URBs that we don't want to lose.
2455                  * examples:
2456                  * 1. while the kernel is cancelling all the packets that make up an
2457                  *    URB, a few of them might complete. so we get back a successful
2458                  *    cancellation *and* some data.
2459                  * 2. we receive a short URB which marks the early completion condition,
2460                  *    so we start cancelling the remaining URBs. however, we're too
2461                  *    slow and another URB completes (or at least completes partially).
2462                  *    (this can't happen since we always use BULK_CONTINUATION.)
2463                  *
2464                  * When this happens, our objectives are not to lose any "surplus" data,
2465                  * and also to stick it at the end of the previously-received data
2466                  * (closing any holes), so that libusb reports the total amount of
2467                  * transferred data and presents it in a contiguous chunk.
2468                  */
2469                 if (urb->actual_length > 0) {
2470                         unsigned char *target = transfer->buffer + itransfer->transferred;
2471                         usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2472                         if (urb->buffer != target) {
2473                                 usbi_dbg("moving surplus data from offset %d to offset %d",
2474                                         (unsigned char *) urb->buffer - transfer->buffer,
2475                                         target - transfer->buffer);
2476                                 memmove(target, urb->buffer, urb->actual_length);
2477                         }
2478                         itransfer->transferred += urb->actual_length;
2479                 }
2480
2481                 if (tpriv->num_retired == tpriv->num_urbs) {
2482                         usbi_dbg("abnormal reap: last URB handled, reporting");
2483                         if (tpriv->reap_action != COMPLETED_EARLY &&
2484                             tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2485                                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2486                         goto completed;
2487                 }
2488                 goto out_unlock;
2489         }
2490
2491         itransfer->transferred += urb->actual_length;
2492
2493         /* Many of these errors can occur on *any* urb of a multi-urb
2494          * transfer.  When they do, we tear down the rest of the transfer.
2495          */
2496         switch (urb->status) {
2497         case 0:
2498                 break;
2499         case -EREMOTEIO: /* short transfer */
2500                 break;
2501         case -ENOENT: /* cancelled */
2502         case -ECONNRESET:
2503                 break;
2504         case -ENODEV:
2505         case -ESHUTDOWN:
2506                 usbi_dbg("device removed");
2507                 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2508                 goto cancel_remaining;
2509         case -EPIPE:
2510                 usbi_dbg("detected endpoint stall");
2511                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2512                         tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2513                 goto cancel_remaining;
2514         case -EOVERFLOW:
2515                 /* overflow can only ever occur in the last urb */
2516                 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2517                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2518                         tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2519                 goto completed;
2520         case -ETIME:
2521         case -EPROTO:
2522         case -EILSEQ:
2523         case -ECOMM:
2524         case -ENOSR:
2525                 usbi_dbg("low level error %d", urb->status);
2526                 tpriv->reap_action = ERROR;
2527                 goto cancel_remaining;
2528         default:
2529                 usbi_warn(ITRANSFER_CTX(itransfer),
2530                         "unrecognised urb status %d", urb->status);
2531                 tpriv->reap_action = ERROR;
2532                 goto cancel_remaining;
2533         }
2534
2535         /* if we're the last urb or we got less data than requested then we're
2536          * done */
2537         if (urb_idx == tpriv->num_urbs - 1) {
2538                 usbi_dbg("last URB in transfer --> complete!");
2539                 goto completed;
2540         } else if (urb->actual_length < urb->buffer_length) {
2541                 usbi_dbg("short transfer %d/%d --> complete!",
2542                         urb->actual_length, urb->buffer_length);
2543                 if (tpriv->reap_action == NORMAL)
2544                         tpriv->reap_action = COMPLETED_EARLY;
2545         } else
2546                 goto out_unlock;
2547
2548 cancel_remaining:
2549         if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2550                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2551
2552         if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2553                 goto completed;
2554
2555         /* cancel remaining urbs and wait for their completion before
2556          * reporting results */
2557         discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2558
2559 out_unlock:
2560         usbi_mutex_unlock(&itransfer->lock);
2561         return 0;
2562
2563 completed:
2564         free(tpriv->urbs);
2565         tpriv->urbs = NULL;
2566         usbi_mutex_unlock(&itransfer->lock);
2567         return CANCELLED == tpriv->reap_action ?
2568                 usbi_handle_transfer_cancellation(itransfer) :
2569                 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2570 }
2571
2572 static int handle_iso_completion(struct usbi_transfer *itransfer,
2573         struct usbfs_urb *urb)
2574 {
2575         struct libusb_transfer *transfer =
2576                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2577         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2578         int num_urbs = tpriv->num_urbs;
2579         int urb_idx = 0;
2580         int i;
2581         enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2582
2583         usbi_mutex_lock(&itransfer->lock);
2584         for (i = 0; i < num_urbs; i++) {
2585                 if (urb == tpriv->iso_urbs[i]) {
2586                         urb_idx = i + 1;
2587                         break;
2588                 }
2589         }
2590         if (urb_idx == 0) {
2591                 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2592                 usbi_mutex_unlock(&itransfer->lock);
2593                 return LIBUSB_ERROR_NOT_FOUND;
2594         }
2595
2596         usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2597                 urb_idx, num_urbs);
2598
2599         /* copy isochronous results back in */
2600
2601         for (i = 0; i < urb->number_of_packets; i++) {
2602                 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2603                 struct libusb_iso_packet_descriptor *lib_desc =
2604                         &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2605                 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2606                 switch (urb_desc->status) {
2607                 case 0:
2608                         break;
2609                 case -ENOENT: /* cancelled */
2610                 case -ECONNRESET:
2611                         break;
2612                 case -ENODEV:
2613                 case -ESHUTDOWN:
2614                         usbi_dbg("device removed");
2615                         lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2616                         break;
2617                 case -EPIPE:
2618                         usbi_dbg("detected endpoint stall");
2619                         lib_desc->status = LIBUSB_TRANSFER_STALL;
2620                         break;
2621                 case -EOVERFLOW:
2622                         usbi_dbg("overflow error");
2623                         lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2624                         break;
2625                 case -ETIME:
2626                 case -EPROTO:
2627                 case -EILSEQ:
2628                 case -ECOMM:
2629                 case -ENOSR:
2630                 case -EXDEV:
2631                         usbi_dbg("low-level USB error %d", urb_desc->status);
2632                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2633                         break;
2634                 default:
2635                         usbi_warn(TRANSFER_CTX(transfer),
2636                                 "unrecognised urb status %d", urb_desc->status);
2637                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2638                         break;
2639                 }
2640                 lib_desc->actual_length = urb_desc->actual_length;
2641         }
2642
2643         tpriv->num_retired++;
2644
2645         if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2646                 usbi_dbg("CANCEL: urb status %d", urb->status);
2647
2648                 if (tpriv->num_retired == num_urbs) {
2649                         usbi_dbg("CANCEL: last URB handled, reporting");
2650                         free_iso_urbs(tpriv);
2651                         if (tpriv->reap_action == CANCELLED) {
2652                                 usbi_mutex_unlock(&itransfer->lock);
2653                                 return usbi_handle_transfer_cancellation(itransfer);
2654                         } else {
2655                                 usbi_mutex_unlock(&itransfer->lock);
2656                                 return usbi_handle_transfer_completion(itransfer,
2657                                         LIBUSB_TRANSFER_ERROR);
2658                         }
2659                 }
2660                 goto out;
2661         }
2662
2663         switch (urb->status) {
2664         case 0:
2665                 break;
2666         case -ENOENT: /* cancelled */
2667         case -ECONNRESET:
2668                 break;
2669         case -ESHUTDOWN:
2670                 usbi_dbg("device removed");
2671                 status = LIBUSB_TRANSFER_NO_DEVICE;
2672                 break;
2673         default:
2674                 usbi_warn(TRANSFER_CTX(transfer),
2675                         "unrecognised urb status %d", urb->status);
2676                 status = LIBUSB_TRANSFER_ERROR;
2677                 break;
2678         }
2679
2680         /* if we're the last urb then we're done */
2681         if (urb_idx == num_urbs) {
2682                 usbi_dbg("last URB in transfer --> complete!");
2683                 free_iso_urbs(tpriv);
2684                 usbi_mutex_unlock(&itransfer->lock);
2685                 return usbi_handle_transfer_completion(itransfer, status);
2686         }
2687
2688 out:
2689         usbi_mutex_unlock(&itransfer->lock);
2690         return 0;
2691 }
2692
2693 static int handle_control_completion(struct usbi_transfer *itransfer,
2694         struct usbfs_urb *urb)
2695 {
2696         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2697         int status;
2698
2699         usbi_mutex_lock(&itransfer->lock);
2700         usbi_dbg("handling completion status %d", urb->status);
2701
2702         itransfer->transferred += urb->actual_length;
2703
2704         if (tpriv->reap_action == CANCELLED) {
2705                 if (urb->status != 0 && urb->status != -ENOENT)
2706                         usbi_warn(ITRANSFER_CTX(itransfer),
2707                                 "cancel: unrecognised urb status %d", urb->status);
2708                 free(tpriv->urbs);
2709                 tpriv->urbs = NULL;
2710                 usbi_mutex_unlock(&itransfer->lock);
2711                 return usbi_handle_transfer_cancellation(itransfer);
2712         }
2713
2714         switch (urb->status) {
2715         case 0:
2716                 status = LIBUSB_TRANSFER_COMPLETED;
2717                 break;
2718         case -ENOENT: /* cancelled */
2719                 status = LIBUSB_TRANSFER_CANCELLED;
2720                 break;
2721         case -ENODEV:
2722         case -ESHUTDOWN:
2723                 usbi_dbg("device removed");
2724                 status = LIBUSB_TRANSFER_NO_DEVICE;
2725                 break;
2726         case -EPIPE:
2727                 usbi_dbg("unsupported control request");
2728                 status = LIBUSB_TRANSFER_STALL;
2729                 break;
2730         case -EOVERFLOW:
2731                 usbi_dbg("control overflow error");
2732                 status = LIBUSB_TRANSFER_OVERFLOW;
2733                 break;
2734         case -ETIME:
2735         case -EPROTO:
2736         case -EILSEQ:
2737         case -ECOMM:
2738         case -ENOSR:
2739                 usbi_dbg("low-level bus error occurred");
2740                 status = LIBUSB_TRANSFER_ERROR;
2741                 break;
2742         default:
2743                 usbi_warn(ITRANSFER_CTX(itransfer),
2744                         "unrecognised urb status %d", urb->status);
2745                 status = LIBUSB_TRANSFER_ERROR;
2746                 break;
2747         }
2748
2749         free(tpriv->urbs);
2750         tpriv->urbs = NULL;
2751         usbi_mutex_unlock(&itransfer->lock);
2752         return usbi_handle_transfer_completion(itransfer, status);
2753 }
2754
2755 static int reap_for_handle(struct libusb_device_handle *handle)
2756 {
2757         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2758         int r;
2759         struct usbfs_urb *urb;
2760         struct usbi_transfer *itransfer;
2761         struct libusb_transfer *transfer;
2762
2763         r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2764         if (r == -1 && errno == EAGAIN)
2765                 return 1;
2766         if (r < 0) {
2767                 if (errno == ENODEV)
2768                         return LIBUSB_ERROR_NO_DEVICE;
2769
2770                 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2771                         r, errno);
2772                 return LIBUSB_ERROR_IO;
2773         }
2774
2775         itransfer = urb->usercontext;
2776         transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2777
2778         usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2779                 urb->actual_length);
2780
2781         switch (transfer->type) {
2782         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2783                 return handle_iso_completion(itransfer, urb);
2784         case LIBUSB_TRANSFER_TYPE_BULK:
2785         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2786         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2787                 return handle_bulk_completion(itransfer, urb);
2788         case LIBUSB_TRANSFER_TYPE_CONTROL:
2789                 return handle_control_completion(itransfer, urb);
2790         default:
2791                 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2792                         transfer->type);
2793                 return LIBUSB_ERROR_OTHER;
2794         }
2795 }
2796
2797 static int op_handle_events(struct libusb_context *ctx,
2798         struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2799 {
2800         int r;
2801         unsigned int i = 0;
2802
2803         usbi_mutex_lock(&ctx->open_devs_lock);
2804         for (i = 0; i < nfds && num_ready > 0; i++) {
2805                 struct pollfd *pollfd = &fds[i];
2806                 struct libusb_device_handle *handle;
2807                 struct linux_device_handle_priv *hpriv = NULL;
2808
2809                 if (!pollfd->revents)
2810                         continue;
2811
2812                 num_ready--;
2813                 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2814                         hpriv = _device_handle_priv(handle);
2815                         if (hpriv->fd == pollfd->fd)
2816                                 break;
2817                 }
2818
2819                 if (!hpriv || hpriv->fd != pollfd->fd) {
2820                         usbi_err(ctx, "cannot find handle for fd %d",
2821                                  pollfd->fd);
2822                         continue;
2823                 }
2824
2825                 if (pollfd->revents & POLLERR) {
2826                         /* remove the fd from the pollfd set so that it doesn't continuously
2827                          * trigger an event, and flag that it has been removed so op_close()
2828                          * doesn't try to remove it a second time */
2829                         usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2830                         hpriv->fd_removed = 1;
2831
2832                         /* device will still be marked as attached if hotplug monitor thread
2833                          * hasn't processed remove event yet */
2834                         usbi_mutex_static_lock(&linux_hotplug_lock);
2835                         if (handle->dev->attached)
2836                                 linux_device_disconnected(handle->dev->bus_number,
2837                                                 handle->dev->device_address);
2838                         usbi_mutex_static_unlock(&linux_hotplug_lock);
2839
2840                         if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2841                                 do {
2842                                         r = reap_for_handle(handle);
2843                                 } while (r == 0);
2844                         }
2845
2846                         usbi_handle_disconnect(handle);
2847                         continue;
2848                 }
2849
2850                 do {
2851                         r = reap_for_handle(handle);
2852                 } while (r == 0);
2853                 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2854                         continue;
2855                 else if (r < 0)
2856                         goto out;
2857         }
2858
2859         r = 0;
2860 out:
2861         usbi_mutex_unlock(&ctx->open_devs_lock);
2862         return r;
2863 }
2864
2865 static int op_clock_gettime(int clk_id, struct timespec *tp)
2866 {
2867         switch (clk_id) {
2868         case USBI_CLOCK_MONOTONIC:
2869                 return clock_gettime(monotonic_clkid, tp);
2870         case USBI_CLOCK_REALTIME:
2871                 return clock_gettime(CLOCK_REALTIME, tp);
2872         default:
2873                 return LIBUSB_ERROR_INVALID_PARAM;
2874   }
2875 }
2876
2877 #ifdef USBI_TIMERFD_AVAILABLE
2878 static clockid_t op_get_timerfd_clockid(void)
2879 {
2880         return monotonic_clkid;
2881
2882 }
2883 #endif
2884
2885 const struct usbi_os_backend usbi_backend = {
2886         .name = "Linux usbfs",
2887         .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2888         .init = op_init,
2889         .exit = op_exit,
2890         .get_device_list = NULL,
2891         .hotplug_poll = op_hotplug_poll,
2892         .get_device_descriptor = op_get_device_descriptor,
2893         .get_active_config_descriptor = op_get_active_config_descriptor,
2894         .get_config_descriptor = op_get_config_descriptor,
2895         .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2896
2897         .open = op_open,
2898         .close = op_close,
2899         .get_configuration = op_get_configuration,
2900         .set_configuration = op_set_configuration,
2901         .claim_interface = op_claim_interface,
2902         .release_interface = op_release_interface,
2903
2904         .set_interface_altsetting = op_set_interface,
2905         .clear_halt = op_clear_halt,
2906         .reset_device = op_reset_device,
2907
2908         .alloc_streams = op_alloc_streams,
2909         .free_streams = op_free_streams,
2910
2911         .dev_mem_alloc = op_dev_mem_alloc,
2912         .dev_mem_free = op_dev_mem_free,
2913
2914         .kernel_driver_active = op_kernel_driver_active,
2915         .detach_kernel_driver = op_detach_kernel_driver,
2916         .attach_kernel_driver = op_attach_kernel_driver,
2917
2918         .destroy_device = op_destroy_device,
2919
2920         .submit_transfer = op_submit_transfer,
2921         .cancel_transfer = op_cancel_transfer,
2922         .clear_transfer_priv = op_clear_transfer_priv,
2923
2924         .handle_events = op_handle_events,
2925
2926         .clock_gettime = op_clock_gettime,
2927
2928 #ifdef USBI_TIMERFD_AVAILABLE
2929         .get_timerfd_clockid = op_get_timerfd_clockid,
2930 #endif
2931
2932         .device_priv_size = sizeof(struct linux_device_priv),
2933         .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2934         .transfer_priv_size = sizeof(struct linux_transfer_priv),
2935 };