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