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