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