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