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