core: Silence 'unhandled case in switch' warning.
[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 | O_CLOEXEC);
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 | O_CLOEXEC);
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 | O_CLOEXEC);
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, "re");
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, (size_t)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, (size_t)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 (priv->sysfs_dir) {
1033                         if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1034                                 dev->parent_dev = libusb_ref_device(it);
1035                                 break;
1036                         }
1037                 }
1038         }
1039         usbi_mutex_unlock(&ctx->usb_devs_lock);
1040
1041         if (!dev->parent_dev && add_parent) {
1042                 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1043                          parent_sysfs_dir);
1044                 sysfs_scan_device(ctx, parent_sysfs_dir);
1045                 add_parent = 0;
1046                 goto retry;
1047         }
1048
1049         usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1050                  dev->parent_dev, parent_sysfs_dir, dev->port_number);
1051
1052         free (parent_sysfs_dir);
1053
1054         return LIBUSB_SUCCESS;
1055 }
1056
1057 int linux_enumerate_device(struct libusb_context *ctx,
1058         uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1059 {
1060         unsigned long session_id;
1061         struct libusb_device *dev;
1062         int r = 0;
1063
1064         /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1065          * will be reused. instead we should add a simple sysfs attribute with
1066          * a session ID. */
1067         session_id = busnum << 8 | devaddr;
1068         usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1069                 session_id);
1070
1071         dev = usbi_get_device_by_session_id(ctx, session_id);
1072         if (dev) {
1073                 /* device already exists in the context */
1074                 usbi_dbg("session_id %ld already exists", session_id);
1075                 libusb_unref_device(dev);
1076                 return LIBUSB_SUCCESS;
1077         }
1078
1079         usbi_dbg("allocating new device for %d/%d (session %ld)",
1080                  busnum, devaddr, session_id);
1081         dev = usbi_alloc_device(ctx, session_id);
1082         if (!dev)
1083                 return LIBUSB_ERROR_NO_MEM;
1084
1085         r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1086         if (r < 0)
1087                 goto out;
1088         r = usbi_sanitize_device(dev);
1089         if (r < 0)
1090                 goto out;
1091
1092         r = linux_get_parent_info(dev, sysfs_dir);
1093         if (r < 0)
1094                 goto out;
1095 out:
1096         if (r < 0)
1097                 libusb_unref_device(dev);
1098         else
1099                 usbi_connect_device(dev);
1100
1101         return r;
1102 }
1103
1104 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1105 {
1106         struct libusb_context *ctx;
1107
1108         usbi_mutex_static_lock(&active_contexts_lock);
1109         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1110                 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1111         }
1112         usbi_mutex_static_unlock(&active_contexts_lock);
1113 }
1114
1115 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1116 {
1117         struct libusb_context *ctx;
1118         struct libusb_device *dev;
1119         unsigned long session_id = busnum << 8 | devaddr;
1120
1121         usbi_mutex_static_lock(&active_contexts_lock);
1122         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1123                 dev = usbi_get_device_by_session_id (ctx, session_id);
1124                 if (NULL != dev) {
1125                         usbi_disconnect_device (dev);
1126                         libusb_unref_device(dev);
1127                 } else {
1128                         usbi_dbg("device not found for session %x", session_id);
1129                 }
1130         }
1131         usbi_mutex_static_unlock(&active_contexts_lock);
1132 }
1133
1134 #if !defined(USE_UDEV)
1135 /* open a bus directory and adds all discovered devices to the context */
1136 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1137 {
1138         DIR *dir;
1139         char dirpath[PATH_MAX];
1140         struct dirent *entry;
1141         int r = LIBUSB_ERROR_IO;
1142
1143         snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1144         usbi_dbg("%s", dirpath);
1145         dir = opendir(dirpath);
1146         if (!dir) {
1147                 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1148                 /* FIXME: should handle valid race conditions like hub unplugged
1149                  * during directory iteration - this is not an error */
1150                 return r;
1151         }
1152
1153         while ((entry = readdir(dir))) {
1154                 int devaddr;
1155
1156                 if (entry->d_name[0] == '.')
1157                         continue;
1158
1159                 devaddr = atoi(entry->d_name);
1160                 if (devaddr == 0) {
1161                         usbi_dbg("unknown dir entry %s", entry->d_name);
1162                         continue;
1163                 }
1164
1165                 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1166                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1167                         continue;
1168                 }
1169
1170                 r = 0;
1171         }
1172
1173         closedir(dir);
1174         return r;
1175 }
1176
1177 static int usbfs_get_device_list(struct libusb_context *ctx)
1178 {
1179         struct dirent *entry;
1180         DIR *buses = opendir(usbfs_path);
1181         int r = 0;
1182
1183         if (!buses) {
1184                 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1185                 return LIBUSB_ERROR_IO;
1186         }
1187
1188         while ((entry = readdir(buses))) {
1189                 int busnum;
1190
1191                 if (entry->d_name[0] == '.')
1192                         continue;
1193
1194                 if (usbdev_names) {
1195                         int devaddr;
1196                         if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1197                                 continue;
1198
1199                         r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1200                         if (r < 0) {
1201                                 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1202                                 continue;
1203                         }
1204                 } else {
1205                         busnum = atoi(entry->d_name);
1206                         if (busnum == 0) {
1207                                 usbi_dbg("unknown dir entry %s", entry->d_name);
1208                                 continue;
1209                         }
1210
1211                         r = usbfs_scan_busdir(ctx, busnum);
1212                         if (r < 0)
1213                                 break;
1214                 }
1215         }
1216
1217         closedir(buses);
1218         return r;
1219
1220 }
1221 #endif
1222
1223 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1224 {
1225         uint8_t busnum, devaddr;
1226         int ret;
1227
1228         ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1229         if (LIBUSB_SUCCESS != ret) {
1230                 return ret;
1231         }
1232
1233         return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1234                 devname);
1235 }
1236
1237 #if !defined(USE_UDEV)
1238 static int sysfs_get_device_list(struct libusb_context *ctx)
1239 {
1240         DIR *devices = opendir(SYSFS_DEVICE_PATH);
1241         struct dirent *entry;
1242         int r = LIBUSB_ERROR_IO;
1243
1244         if (!devices) {
1245                 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1246                 return r;
1247         }
1248
1249         while ((entry = readdir(devices))) {
1250                 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1251                                 || strchr(entry->d_name, ':'))
1252                         continue;
1253
1254                 if (sysfs_scan_device(ctx, entry->d_name)) {
1255                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1256                         continue;
1257                 }
1258
1259                 r = 0;
1260         }
1261
1262         closedir(devices);
1263         return r;
1264 }
1265
1266 static int linux_default_scan_devices (struct libusb_context *ctx)
1267 {
1268         /* we can retrieve device list and descriptors from sysfs or usbfs.
1269          * sysfs is preferable, because if we use usbfs we end up resuming
1270          * any autosuspended USB devices. however, sysfs is not available
1271          * everywhere, so we need a usbfs fallback too.
1272          *
1273          * as described in the "sysfs vs usbfs" comment at the top of this
1274          * file, sometimes we have sysfs but not enough information to
1275          * relate sysfs devices to usbfs nodes.  op_init() determines the
1276          * adequacy of sysfs and sets sysfs_can_relate_devices.
1277          */
1278         if (sysfs_can_relate_devices != 0)
1279                 return sysfs_get_device_list(ctx);
1280         else
1281                 return usbfs_get_device_list(ctx);
1282 }
1283 #endif
1284
1285 static int op_open(struct libusb_device_handle *handle)
1286 {
1287         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1288         int r;
1289
1290         hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1291         if (hpriv->fd < 0) {
1292                 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1293                         /* device will still be marked as attached if hotplug monitor thread
1294                          * hasn't processed remove event yet */
1295                         usbi_mutex_static_lock(&linux_hotplug_lock);
1296                         if (handle->dev->attached) {
1297                                 usbi_dbg("open failed with no device, but device still attached");
1298                                 linux_device_disconnected(handle->dev->bus_number,
1299                                                 handle->dev->device_address);
1300                         }
1301                         usbi_mutex_static_unlock(&linux_hotplug_lock);
1302                 }
1303                 return hpriv->fd;
1304         }
1305
1306         r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1307         if (r < 0) {
1308                 if (errno == ENOTTY)
1309                         usbi_dbg("getcap not available");
1310                 else
1311                         usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1312                 hpriv->caps = 0;
1313                 if (supports_flag_zero_packet)
1314                         hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1315                 if (supports_flag_bulk_continuation)
1316                         hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1317         }
1318
1319         r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1320         if (r < 0)
1321                 close(hpriv->fd);
1322
1323         return r;
1324 }
1325
1326 static void op_close(struct libusb_device_handle *dev_handle)
1327 {
1328         struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1329         /* fd may have already been removed by POLLERR condition in op_handle_events() */
1330         if (!hpriv->fd_removed)
1331                 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1332         close(hpriv->fd);
1333 }
1334
1335 static int op_get_configuration(struct libusb_device_handle *handle,
1336         int *config)
1337 {
1338         int r;
1339
1340         if (sysfs_can_relate_devices) {
1341                 r = sysfs_get_active_config(handle->dev, config);
1342         } else {
1343                 r = usbfs_get_active_config(handle->dev,
1344                                             _device_handle_priv(handle)->fd);
1345                 if (r == LIBUSB_SUCCESS)
1346                         *config = _device_priv(handle->dev)->active_config;
1347         }
1348         if (r < 0)
1349                 return r;
1350
1351         if (*config == -1) {
1352                 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1353                 *config = 0;
1354         }
1355
1356         return 0;
1357 }
1358
1359 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1360 {
1361         struct linux_device_priv *priv = _device_priv(handle->dev);
1362         int fd = _device_handle_priv(handle)->fd;
1363         int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1364         if (r) {
1365                 if (errno == EINVAL)
1366                         return LIBUSB_ERROR_NOT_FOUND;
1367                 else if (errno == EBUSY)
1368                         return LIBUSB_ERROR_BUSY;
1369                 else if (errno == ENODEV)
1370                         return LIBUSB_ERROR_NO_DEVICE;
1371
1372                 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1373                 return LIBUSB_ERROR_OTHER;
1374         }
1375
1376         /* update our cached active config descriptor */
1377         priv->active_config = config;
1378
1379         return LIBUSB_SUCCESS;
1380 }
1381
1382 static int claim_interface(struct libusb_device_handle *handle, int iface)
1383 {
1384         int fd = _device_handle_priv(handle)->fd;
1385         int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1386         if (r) {
1387                 if (errno == ENOENT)
1388                         return LIBUSB_ERROR_NOT_FOUND;
1389                 else if (errno == EBUSY)
1390                         return LIBUSB_ERROR_BUSY;
1391                 else if (errno == ENODEV)
1392                         return LIBUSB_ERROR_NO_DEVICE;
1393
1394                 usbi_err(HANDLE_CTX(handle),
1395                         "claim interface failed, error %d errno %d", r, errno);
1396                 return LIBUSB_ERROR_OTHER;
1397         }
1398         return 0;
1399 }
1400
1401 static int release_interface(struct libusb_device_handle *handle, int iface)
1402 {
1403         int fd = _device_handle_priv(handle)->fd;
1404         int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1405         if (r) {
1406                 if (errno == ENODEV)
1407                         return LIBUSB_ERROR_NO_DEVICE;
1408
1409                 usbi_err(HANDLE_CTX(handle),
1410                         "release interface failed, error %d errno %d", r, errno);
1411                 return LIBUSB_ERROR_OTHER;
1412         }
1413         return 0;
1414 }
1415
1416 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1417         int altsetting)
1418 {
1419         int fd = _device_handle_priv(handle)->fd;
1420         struct usbfs_setinterface setintf;
1421         int r;
1422
1423         setintf.interface = iface;
1424         setintf.altsetting = altsetting;
1425         r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1426         if (r) {
1427                 if (errno == EINVAL)
1428                         return LIBUSB_ERROR_NOT_FOUND;
1429                 else if (errno == ENODEV)
1430                         return LIBUSB_ERROR_NO_DEVICE;
1431
1432                 usbi_err(HANDLE_CTX(handle),
1433                         "setintf failed error %d errno %d", r, errno);
1434                 return LIBUSB_ERROR_OTHER;
1435         }
1436
1437         return 0;
1438 }
1439
1440 static int op_clear_halt(struct libusb_device_handle *handle,
1441         unsigned char endpoint)
1442 {
1443         int fd = _device_handle_priv(handle)->fd;
1444         unsigned int _endpoint = endpoint;
1445         int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1446         if (r) {
1447                 if (errno == ENOENT)
1448                         return LIBUSB_ERROR_NOT_FOUND;
1449                 else if (errno == ENODEV)
1450                         return LIBUSB_ERROR_NO_DEVICE;
1451
1452                 usbi_err(HANDLE_CTX(handle),
1453                         "clear_halt failed error %d errno %d", r, errno);
1454                 return LIBUSB_ERROR_OTHER;
1455         }
1456
1457         return 0;
1458 }
1459
1460 static int op_reset_device(struct libusb_device_handle *handle)
1461 {
1462         int fd = _device_handle_priv(handle)->fd;
1463         int i, r, ret = 0;
1464
1465         /* Doing a device reset will cause the usbfs driver to get unbound
1466            from any interfaces it is bound to. By voluntarily unbinding
1467            the usbfs driver ourself, we stop the kernel from rebinding
1468            the interface after reset (which would end up with the interface
1469            getting bound to the in kernel driver if any). */
1470         for (i = 0; i < USB_MAXINTERFACES; i++) {
1471                 if (handle->claimed_interfaces & (1L << i)) {
1472                         release_interface(handle, i);
1473                 }
1474         }
1475
1476         usbi_mutex_lock(&handle->lock);
1477         r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1478         if (r) {
1479                 if (errno == ENODEV) {
1480                         ret = LIBUSB_ERROR_NOT_FOUND;
1481                         goto out;
1482                 }
1483
1484                 usbi_err(HANDLE_CTX(handle),
1485                         "reset failed error %d errno %d", r, errno);
1486                 ret = LIBUSB_ERROR_OTHER;
1487                 goto out;
1488         }
1489
1490         /* And re-claim any interfaces which were claimed before the reset */
1491         for (i = 0; i < USB_MAXINTERFACES; i++) {
1492                 if (handle->claimed_interfaces & (1L << i)) {
1493                         /*
1494                          * A driver may have completed modprobing during
1495                          * IOCTL_USBFS_RESET, and bound itself as soon as
1496                          * IOCTL_USBFS_RESET released the device lock
1497                          */
1498                         r = detach_kernel_driver_and_claim(handle, i);
1499                         if (r) {
1500                                 usbi_warn(HANDLE_CTX(handle),
1501                                         "failed to re-claim interface %d after reset: %s",
1502                                         i, libusb_error_name(r));
1503                                 handle->claimed_interfaces &= ~(1L << i);
1504                                 ret = LIBUSB_ERROR_NOT_FOUND;
1505                         }
1506                 }
1507         }
1508 out:
1509         usbi_mutex_unlock(&handle->lock);
1510         return ret;
1511 }
1512
1513 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1514         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1515 {
1516         int r, fd = _device_handle_priv(handle)->fd;
1517         struct usbfs_streams *streams;
1518
1519         if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1520                 return LIBUSB_ERROR_INVALID_PARAM;
1521
1522         streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1523         if (!streams)
1524                 return LIBUSB_ERROR_NO_MEM;
1525
1526         streams->num_streams = num_streams;
1527         streams->num_eps = num_endpoints;
1528         memcpy(streams->eps, endpoints, num_endpoints);
1529
1530         r = ioctl(fd, req, streams);
1531
1532         free(streams);
1533
1534         if (r < 0) {
1535                 if (errno == ENOTTY)
1536                         return LIBUSB_ERROR_NOT_SUPPORTED;
1537                 else if (errno == EINVAL)
1538                         return LIBUSB_ERROR_INVALID_PARAM;
1539                 else if (errno == ENODEV)
1540                         return LIBUSB_ERROR_NO_DEVICE;
1541
1542                 usbi_err(HANDLE_CTX(handle),
1543                         "streams-ioctl failed error %d errno %d", r, errno);
1544                 return LIBUSB_ERROR_OTHER;
1545         }
1546         return r;
1547 }
1548
1549 static int op_alloc_streams(struct libusb_device_handle *handle,
1550         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1551 {
1552         return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1553                                 num_streams, endpoints, num_endpoints);
1554 }
1555
1556 static int op_free_streams(struct libusb_device_handle *handle,
1557                 unsigned char *endpoints, int num_endpoints)
1558 {
1559         return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1560                                 endpoints, num_endpoints);
1561 }
1562
1563 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1564         size_t len)
1565 {
1566         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1567         unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1568                 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1569         if (buffer == MAP_FAILED) {
1570                 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1571                         errno);
1572                 return NULL;
1573         }
1574         return buffer;
1575 }
1576
1577 static int op_dev_mem_free(struct libusb_device_handle *handle,
1578         unsigned char *buffer, size_t len)
1579 {
1580         if (munmap(buffer, len) != 0) {
1581                 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1582                         errno);
1583                 return LIBUSB_ERROR_OTHER;
1584         } else {
1585                 return LIBUSB_SUCCESS;
1586         }
1587 }
1588
1589 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1590         int interface)
1591 {
1592         int fd = _device_handle_priv(handle)->fd;
1593         struct usbfs_getdriver getdrv;
1594         int r;
1595
1596         getdrv.interface = interface;
1597         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1598         if (r) {
1599                 if (errno == ENODATA)
1600                         return 0;
1601                 else if (errno == ENODEV)
1602                         return LIBUSB_ERROR_NO_DEVICE;
1603
1604                 usbi_err(HANDLE_CTX(handle),
1605                         "get driver failed error %d errno %d", r, errno);
1606                 return LIBUSB_ERROR_OTHER;
1607         }
1608
1609         return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1610 }
1611
1612 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1613         int interface)
1614 {
1615         int fd = _device_handle_priv(handle)->fd;
1616         struct usbfs_ioctl command;
1617         struct usbfs_getdriver getdrv;
1618         int r;
1619
1620         command.ifno = interface;
1621         command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1622         command.data = NULL;
1623
1624         getdrv.interface = interface;
1625         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1626         if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1627                 return LIBUSB_ERROR_NOT_FOUND;
1628
1629         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1630         if (r) {
1631                 if (errno == ENODATA)
1632                         return LIBUSB_ERROR_NOT_FOUND;
1633                 else if (errno == EINVAL)
1634                         return LIBUSB_ERROR_INVALID_PARAM;
1635                 else if (errno == ENODEV)
1636                         return LIBUSB_ERROR_NO_DEVICE;
1637
1638                 usbi_err(HANDLE_CTX(handle),
1639                         "detach failed error %d errno %d", r, errno);
1640                 return LIBUSB_ERROR_OTHER;
1641         }
1642
1643         return 0;
1644 }
1645
1646 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1647         int interface)
1648 {
1649         int fd = _device_handle_priv(handle)->fd;
1650         struct usbfs_ioctl command;
1651         int r;
1652
1653         command.ifno = interface;
1654         command.ioctl_code = IOCTL_USBFS_CONNECT;
1655         command.data = NULL;
1656
1657         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1658         if (r < 0) {
1659                 if (errno == ENODATA)
1660                         return LIBUSB_ERROR_NOT_FOUND;
1661                 else if (errno == EINVAL)
1662                         return LIBUSB_ERROR_INVALID_PARAM;
1663                 else if (errno == ENODEV)
1664                         return LIBUSB_ERROR_NO_DEVICE;
1665                 else if (errno == EBUSY)
1666                         return LIBUSB_ERROR_BUSY;
1667
1668                 usbi_err(HANDLE_CTX(handle),
1669                         "attach failed error %d errno %d", r, errno);
1670                 return LIBUSB_ERROR_OTHER;
1671         } else if (r == 0) {
1672                 return LIBUSB_ERROR_NOT_FOUND;
1673         }
1674
1675         return 0;
1676 }
1677
1678 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1679         int interface)
1680 {
1681         struct usbfs_disconnect_claim dc;
1682         int r, fd = _device_handle_priv(handle)->fd;
1683
1684         dc.interface = interface;
1685         strcpy(dc.driver, "usbfs");
1686         dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1687         r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1688         if (r == 0 || (r != 0 && errno != ENOTTY)) {
1689                 if (r == 0)
1690                         return 0;
1691
1692                 switch (errno) {
1693                 case EBUSY:
1694                         return LIBUSB_ERROR_BUSY;
1695                 case EINVAL:
1696                         return LIBUSB_ERROR_INVALID_PARAM;
1697                 case ENODEV:
1698                         return LIBUSB_ERROR_NO_DEVICE;
1699                 }
1700                 usbi_err(HANDLE_CTX(handle),
1701                         "disconnect-and-claim failed errno %d", errno);
1702                 return LIBUSB_ERROR_OTHER;
1703         }
1704
1705         /* Fallback code for kernels which don't support the
1706            disconnect-and-claim ioctl */
1707         r = op_detach_kernel_driver(handle, interface);
1708         if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1709                 return r;
1710
1711         return claim_interface(handle, interface);
1712 }
1713
1714 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1715 {
1716         if (handle->auto_detach_kernel_driver)
1717                 return detach_kernel_driver_and_claim(handle, iface);
1718         else
1719                 return claim_interface(handle, iface);
1720 }
1721
1722 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1723 {
1724         int r;
1725
1726         r = release_interface(handle, iface);
1727         if (r)
1728                 return r;
1729
1730         if (handle->auto_detach_kernel_driver)
1731                 op_attach_kernel_driver(handle, iface);
1732
1733         return 0;
1734 }
1735
1736 static void op_destroy_device(struct libusb_device *dev)
1737 {
1738         struct linux_device_priv *priv = _device_priv(dev);
1739         if (priv->descriptors)
1740                 free(priv->descriptors);
1741         if (priv->sysfs_dir)
1742                 free(priv->sysfs_dir);
1743 }
1744
1745 /* URBs are discarded in reverse order of submission to avoid races. */
1746 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1747 {
1748         struct libusb_transfer *transfer =
1749                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1750         struct linux_transfer_priv *tpriv =
1751                 usbi_transfer_get_os_priv(itransfer);
1752         struct linux_device_handle_priv *dpriv =
1753                 _device_handle_priv(transfer->dev_handle);
1754         int i, ret = 0;
1755         struct usbfs_urb *urb;
1756
1757         for (i = last_plus_one - 1; i >= first; i--) {
1758                 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1759                         urb = tpriv->iso_urbs[i];
1760                 else
1761                         urb = &tpriv->urbs[i];
1762
1763                 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1764                         continue;
1765
1766                 if (EINVAL == errno) {
1767                         usbi_dbg("URB not found --> assuming ready to be reaped");
1768                         if (i == (last_plus_one - 1))
1769                                 ret = LIBUSB_ERROR_NOT_FOUND;
1770                 } else if (ENODEV == errno) {
1771                         usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1772                         ret = LIBUSB_ERROR_NO_DEVICE;
1773                 } else {
1774                         usbi_warn(TRANSFER_CTX(transfer),
1775                                 "unrecognised discard errno %d", errno);
1776                         ret = LIBUSB_ERROR_OTHER;
1777                 }
1778         }
1779         return ret;
1780 }
1781
1782 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1783 {
1784         int i;
1785         for (i = 0; i < tpriv->num_urbs; i++) {
1786                 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1787                 if (!urb)
1788                         break;
1789                 free(urb);
1790         }
1791
1792         free(tpriv->iso_urbs);
1793         tpriv->iso_urbs = NULL;
1794 }
1795
1796 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1797 {
1798         struct libusb_transfer *transfer =
1799                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1800         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1801         struct linux_device_handle_priv *dpriv =
1802                 _device_handle_priv(transfer->dev_handle);
1803         struct usbfs_urb *urbs;
1804         int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1805                 == LIBUSB_ENDPOINT_OUT;
1806         int bulk_buffer_len, use_bulk_continuation;
1807         int r;
1808         int i;
1809
1810         if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1811                         !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1812                 return LIBUSB_ERROR_NOT_SUPPORTED;
1813
1814         /*
1815          * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1816          * around this by splitting large transfers into 16k blocks, and then
1817          * submit all urbs at once. it would be simpler to submit one urb at
1818          * a time, but there is a big performance gain doing it this way.
1819          *
1820          * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1821          * using arbritary large transfers can still be a bad idea though, as
1822          * the kernel needs to allocate physical contiguous memory for this,
1823          * which may fail for large buffers.
1824          *
1825          * The kernel solves this problem by splitting the transfer into
1826          * blocks itself when the host-controller is scatter-gather capable
1827          * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1828          *
1829          * Last, there is the issue of short-transfers when splitting, for
1830          * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1831          * is needed, but this is not always available.
1832          */
1833         if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1834                 /* Good! Just submit everything in one go */
1835                 bulk_buffer_len = transfer->length ? transfer->length : 1;
1836                 use_bulk_continuation = 0;
1837         } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1838                 /* Split the transfers and use bulk-continuation to
1839                    avoid issues with short-transfers */
1840                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1841                 use_bulk_continuation = 1;
1842         } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1843                 /* Don't split, assume the kernel can alloc the buffer
1844                    (otherwise the submit will fail with -ENOMEM) */
1845                 bulk_buffer_len = transfer->length ? transfer->length : 1;
1846                 use_bulk_continuation = 0;
1847         } else {
1848                 /* Bad, splitting without bulk-continuation, short transfers
1849                    which end before the last urb will not work reliable! */
1850                 /* Note we don't warn here as this is "normal" on kernels <
1851                    2.6.32 and not a problem for most applications */
1852                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1853                 use_bulk_continuation = 0;
1854         }
1855
1856         int num_urbs = transfer->length / bulk_buffer_len;
1857         int last_urb_partial = 0;
1858
1859         if (transfer->length == 0) {
1860                 num_urbs = 1;
1861         } else if ((transfer->length % bulk_buffer_len) > 0) {
1862                 last_urb_partial = 1;
1863                 num_urbs++;
1864         }
1865         usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1866                 transfer->length);
1867         urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1868         if (!urbs)
1869                 return LIBUSB_ERROR_NO_MEM;
1870         tpriv->urbs = urbs;
1871         tpriv->num_urbs = num_urbs;
1872         tpriv->num_retired = 0;
1873         tpriv->reap_action = NORMAL;
1874         tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1875
1876         for (i = 0; i < num_urbs; i++) {
1877                 struct usbfs_urb *urb = &urbs[i];
1878                 urb->usercontext = itransfer;
1879                 switch (transfer->type) {
1880                 case LIBUSB_TRANSFER_TYPE_BULK:
1881                         urb->type = USBFS_URB_TYPE_BULK;
1882                         urb->stream_id = 0;
1883                         break;
1884                 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1885                         urb->type = USBFS_URB_TYPE_BULK;
1886                         urb->stream_id = itransfer->stream_id;
1887                         break;
1888                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1889                         urb->type = USBFS_URB_TYPE_INTERRUPT;
1890                         break;
1891                 }
1892                 urb->endpoint = transfer->endpoint;
1893                 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1894                 /* don't set the short not ok flag for the last URB */
1895                 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1896                         urb->flags = USBFS_URB_SHORT_NOT_OK;
1897                 if (i == num_urbs - 1 && last_urb_partial)
1898                         urb->buffer_length = transfer->length % bulk_buffer_len;
1899                 else if (transfer->length == 0)
1900                         urb->buffer_length = 0;
1901                 else
1902                         urb->buffer_length = bulk_buffer_len;
1903
1904                 if (i > 0 && use_bulk_continuation)
1905                         urb->flags |= USBFS_URB_BULK_CONTINUATION;
1906
1907                 /* we have already checked that the flag is supported */
1908                 if (is_out && i == num_urbs - 1 &&
1909                     transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1910                         urb->flags |= USBFS_URB_ZERO_PACKET;
1911
1912                 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1913                 if (r < 0) {
1914                         if (errno == ENODEV) {
1915                                 r = LIBUSB_ERROR_NO_DEVICE;
1916                         } else {
1917                                 usbi_err(TRANSFER_CTX(transfer),
1918                                         "submiturb failed error %d errno=%d", r, errno);
1919                                 r = LIBUSB_ERROR_IO;
1920                         }
1921
1922                         /* if the first URB submission fails, we can simply free up and
1923                          * return failure immediately. */
1924                         if (i == 0) {
1925                                 usbi_dbg("first URB failed, easy peasy");
1926                                 free(urbs);
1927                                 tpriv->urbs = NULL;
1928                                 return r;
1929                         }
1930
1931                         /* if it's not the first URB that failed, the situation is a bit
1932                          * tricky. we may need to discard all previous URBs. there are
1933                          * complications:
1934                          *  - discarding is asynchronous - discarded urbs will be reaped
1935                          *    later. the user must not have freed the transfer when the
1936                          *    discarded URBs are reaped, otherwise libusb will be using
1937                          *    freed memory.
1938                          *  - the earlier URBs may have completed successfully and we do
1939                          *    not want to throw away any data.
1940                          *  - this URB failing may be no error; EREMOTEIO means that
1941                          *    this transfer simply didn't need all the URBs we submitted
1942                          * so, we report that the transfer was submitted successfully and
1943                          * in case of error we discard all previous URBs. later when
1944                          * the final reap completes we can report error to the user,
1945                          * or success if an earlier URB was completed successfully.
1946                          */
1947                         tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1948
1949                         /* The URBs we haven't submitted yet we count as already
1950                          * retired. */
1951                         tpriv->num_retired += num_urbs - i;
1952
1953                         /* If we completed short then don't try to discard. */
1954                         if (COMPLETED_EARLY == tpriv->reap_action)
1955                                 return 0;
1956
1957                         discard_urbs(itransfer, 0, i);
1958
1959                         usbi_dbg("reporting successful submission but waiting for %d "
1960                                 "discards before reporting error", i);
1961                         return 0;
1962                 }
1963         }
1964
1965         return 0;
1966 }
1967
1968 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1969 {
1970         struct libusb_transfer *transfer =
1971                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1972         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1973         struct linux_device_handle_priv *dpriv =
1974                 _device_handle_priv(transfer->dev_handle);
1975         struct usbfs_urb **urbs;
1976         size_t alloc_size;
1977         int num_packets = transfer->num_iso_packets;
1978         int i;
1979         int this_urb_len = 0;
1980         int num_urbs = 1;
1981         int packet_offset = 0;
1982         unsigned int packet_len;
1983         unsigned char *urb_buffer = transfer->buffer;
1984
1985         /* usbfs places arbitrary limits on iso URBs. this limit has changed
1986          * at least three times, and it's difficult to accurately detect which
1987          * limit this running kernel might impose. so we attempt to submit
1988          * whatever the user has provided. if the kernel rejects the request
1989          * due to its size, we return an error indicating such to the user.
1990          */
1991
1992         /* calculate how many URBs we need */
1993         for (i = 0; i < num_packets; i++) {
1994                 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1995                 packet_len = transfer->iso_packet_desc[i].length;
1996
1997                 if (packet_len > space_remaining) {
1998                         num_urbs++;
1999                         this_urb_len = packet_len;
2000                         /* check that we can actually support this packet length */
2001                         if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2002                                 return LIBUSB_ERROR_INVALID_PARAM;
2003                 } else {
2004                         this_urb_len += packet_len;
2005                 }
2006         }
2007         usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2008
2009         urbs = calloc(num_urbs, sizeof(*urbs));
2010         if (!urbs)
2011                 return LIBUSB_ERROR_NO_MEM;
2012
2013         tpriv->iso_urbs = urbs;
2014         tpriv->num_urbs = num_urbs;
2015         tpriv->num_retired = 0;
2016         tpriv->reap_action = NORMAL;
2017         tpriv->iso_packet_offset = 0;
2018
2019         /* allocate + initialize each URB with the correct number of packets */
2020         for (i = 0; i < num_urbs; i++) {
2021                 struct usbfs_urb *urb;
2022                 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2023                 int urb_packet_offset = 0;
2024                 unsigned char *urb_buffer_orig = urb_buffer;
2025                 int j;
2026                 int k;
2027
2028                 /* swallow up all the packets we can fit into this URB */
2029                 while (packet_offset < transfer->num_iso_packets) {
2030                         packet_len = transfer->iso_packet_desc[packet_offset].length;
2031                         if (packet_len <= space_remaining_in_urb) {
2032                                 /* throw it in */
2033                                 urb_packet_offset++;
2034                                 packet_offset++;
2035                                 space_remaining_in_urb -= packet_len;
2036                                 urb_buffer += packet_len;
2037                         } else {
2038                                 /* it can't fit, save it for the next URB */
2039                                 break;
2040                         }
2041                 }
2042
2043                 alloc_size = sizeof(*urb)
2044                         + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2045                 urb = calloc(1, alloc_size);
2046                 if (!urb) {
2047                         free_iso_urbs(tpriv);
2048                         return LIBUSB_ERROR_NO_MEM;
2049                 }
2050                 urbs[i] = urb;
2051
2052                 /* populate packet lengths */
2053                 for (j = 0, k = packet_offset - urb_packet_offset;
2054                                 k < packet_offset; k++, j++) {
2055                         packet_len = transfer->iso_packet_desc[k].length;
2056                         urb->iso_frame_desc[j].length = packet_len;
2057                 }
2058
2059                 urb->usercontext = itransfer;
2060                 urb->type = USBFS_URB_TYPE_ISO;
2061                 /* FIXME: interface for non-ASAP data? */
2062                 urb->flags = USBFS_URB_ISO_ASAP;
2063                 urb->endpoint = transfer->endpoint;
2064                 urb->number_of_packets = urb_packet_offset;
2065                 urb->buffer = urb_buffer_orig;
2066         }
2067
2068         /* submit URBs */
2069         for (i = 0; i < num_urbs; i++) {
2070                 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2071                 if (r < 0) {
2072                         if (errno == ENODEV) {
2073                                 r = LIBUSB_ERROR_NO_DEVICE;
2074                         } else if (errno == EINVAL) {
2075                                 usbi_warn(TRANSFER_CTX(transfer),
2076                                         "submiturb failed, transfer too large");
2077                                 r = LIBUSB_ERROR_INVALID_PARAM;
2078                         } else {
2079                                 usbi_err(TRANSFER_CTX(transfer),
2080                                         "submiturb failed error %d errno=%d", r, errno);
2081                                 r = LIBUSB_ERROR_IO;
2082                         }
2083
2084                         /* if the first URB submission fails, we can simply free up and
2085                          * return failure immediately. */
2086                         if (i == 0) {
2087                                 usbi_dbg("first URB failed, easy peasy");
2088                                 free_iso_urbs(tpriv);
2089                                 return r;
2090                         }
2091
2092                         /* if it's not the first URB that failed, the situation is a bit
2093                          * tricky. we must discard all previous URBs. there are
2094                          * complications:
2095                          *  - discarding is asynchronous - discarded urbs will be reaped
2096                          *    later. the user must not have freed the transfer when the
2097                          *    discarded URBs are reaped, otherwise libusb will be using
2098                          *    freed memory.
2099                          *  - the earlier URBs may have completed successfully and we do
2100                          *    not want to throw away any data.
2101                          * so, in this case we discard all the previous URBs BUT we report
2102                          * that the transfer was submitted successfully. then later when
2103                          * the final discard completes we can report error to the user.
2104                          */
2105                         tpriv->reap_action = SUBMIT_FAILED;
2106
2107                         /* The URBs we haven't submitted yet we count as already
2108                          * retired. */
2109                         tpriv->num_retired = num_urbs - i;
2110                         discard_urbs(itransfer, 0, i);
2111
2112                         usbi_dbg("reporting successful submission but waiting for %d "
2113                                 "discards before reporting error", i);
2114                         return 0;
2115                 }
2116         }
2117
2118         return 0;
2119 }
2120
2121 static int submit_control_transfer(struct usbi_transfer *itransfer)
2122 {
2123         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2124         struct libusb_transfer *transfer =
2125                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2126         struct linux_device_handle_priv *dpriv =
2127                 _device_handle_priv(transfer->dev_handle);
2128         struct usbfs_urb *urb;
2129         int r;
2130
2131         if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2132                 return LIBUSB_ERROR_INVALID_PARAM;
2133
2134         urb = calloc(1, sizeof(struct usbfs_urb));
2135         if (!urb)
2136                 return LIBUSB_ERROR_NO_MEM;
2137         tpriv->urbs = urb;
2138         tpriv->num_urbs = 1;
2139         tpriv->reap_action = NORMAL;
2140
2141         urb->usercontext = itransfer;
2142         urb->type = USBFS_URB_TYPE_CONTROL;
2143         urb->endpoint = transfer->endpoint;
2144         urb->buffer = transfer->buffer;
2145         urb->buffer_length = transfer->length;
2146
2147         r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2148         if (r < 0) {
2149                 free(urb);
2150                 tpriv->urbs = NULL;
2151                 if (errno == ENODEV)
2152                         return LIBUSB_ERROR_NO_DEVICE;
2153
2154                 usbi_err(TRANSFER_CTX(transfer),
2155                         "submiturb failed error %d errno=%d", r, errno);
2156                 return LIBUSB_ERROR_IO;
2157         }
2158         return 0;
2159 }
2160
2161 static int op_submit_transfer(struct usbi_transfer *itransfer)
2162 {
2163         struct libusb_transfer *transfer =
2164                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2165
2166         switch (transfer->type) {
2167         case LIBUSB_TRANSFER_TYPE_CONTROL:
2168                 return submit_control_transfer(itransfer);
2169         case LIBUSB_TRANSFER_TYPE_BULK:
2170         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2171                 return submit_bulk_transfer(itransfer);
2172         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2173                 return submit_bulk_transfer(itransfer);
2174         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2175                 return submit_iso_transfer(itransfer);
2176         default:
2177                 usbi_err(TRANSFER_CTX(transfer),
2178                         "unknown endpoint type %d", transfer->type);
2179                 return LIBUSB_ERROR_INVALID_PARAM;
2180         }
2181 }
2182
2183 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2184 {
2185         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2186         struct libusb_transfer *transfer =
2187                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2188         int r;
2189
2190         if (!tpriv->urbs)
2191                 return LIBUSB_ERROR_NOT_FOUND;
2192
2193         r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2194         if (r != 0)
2195                 return r;
2196
2197         switch (transfer->type) {
2198         case LIBUSB_TRANSFER_TYPE_BULK:
2199         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2200                 if (tpriv->reap_action == ERROR)
2201                         break;
2202                 /* else, fall through */
2203         default:
2204                 tpriv->reap_action = CANCELLED;
2205         }
2206
2207         return 0;
2208 }
2209
2210 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2211 {
2212         struct libusb_transfer *transfer =
2213                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2214         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2215
2216         /* urbs can be freed also in submit_transfer so lock mutex first */
2217         switch (transfer->type) {
2218         case LIBUSB_TRANSFER_TYPE_CONTROL:
2219         case LIBUSB_TRANSFER_TYPE_BULK:
2220         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2221         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2222                 if (tpriv->urbs) {
2223                         free(tpriv->urbs);
2224                         tpriv->urbs = NULL;
2225                 }
2226                 break;
2227         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2228                 if (tpriv->iso_urbs) {
2229                         free_iso_urbs(tpriv);
2230                         tpriv->iso_urbs = NULL;
2231                 }
2232                 break;
2233         default:
2234                 usbi_err(TRANSFER_CTX(transfer),
2235                         "unknown endpoint type %d", transfer->type);
2236         }
2237 }
2238
2239 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2240         struct usbfs_urb *urb)
2241 {
2242         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2243         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2244         int urb_idx = urb - tpriv->urbs;
2245
2246         usbi_mutex_lock(&itransfer->lock);
2247         usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2248                 urb_idx + 1, tpriv->num_urbs);
2249
2250         tpriv->num_retired++;
2251
2252         if (tpriv->reap_action != NORMAL) {
2253                 /* cancelled, submit_fail, or completed early */
2254                 usbi_dbg("abnormal reap: urb status %d", urb->status);
2255
2256                 /* even though we're in the process of cancelling, it's possible that
2257                  * we may receive some data in these URBs that we don't want to lose.
2258                  * examples:
2259                  * 1. while the kernel is cancelling all the packets that make up an
2260                  *    URB, a few of them might complete. so we get back a successful
2261                  *    cancellation *and* some data.
2262                  * 2. we receive a short URB which marks the early completion condition,
2263                  *    so we start cancelling the remaining URBs. however, we're too
2264                  *    slow and another URB completes (or at least completes partially).
2265                  *    (this can't happen since we always use BULK_CONTINUATION.)
2266                  *
2267                  * When this happens, our objectives are not to lose any "surplus" data,
2268                  * and also to stick it at the end of the previously-received data
2269                  * (closing any holes), so that libusb reports the total amount of
2270                  * transferred data and presents it in a contiguous chunk.
2271                  */
2272                 if (urb->actual_length > 0) {
2273                         unsigned char *target = transfer->buffer + itransfer->transferred;
2274                         usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2275                         if (urb->buffer != target) {
2276                                 usbi_dbg("moving surplus data from offset %d to offset %d",
2277                                         (unsigned char *) urb->buffer - transfer->buffer,
2278                                         target - transfer->buffer);
2279                                 memmove(target, urb->buffer, urb->actual_length);
2280                         }
2281                         itransfer->transferred += urb->actual_length;
2282                 }
2283
2284                 if (tpriv->num_retired == tpriv->num_urbs) {
2285                         usbi_dbg("abnormal reap: last URB handled, reporting");
2286                         if (tpriv->reap_action != COMPLETED_EARLY &&
2287                             tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2288                                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2289                         goto completed;
2290                 }
2291                 goto out_unlock;
2292         }
2293
2294         itransfer->transferred += urb->actual_length;
2295
2296         /* Many of these errors can occur on *any* urb of a multi-urb
2297          * transfer.  When they do, we tear down the rest of the transfer.
2298          */
2299         switch (urb->status) {
2300         case 0:
2301                 break;
2302         case -EREMOTEIO: /* short transfer */
2303                 break;
2304         case -ENOENT: /* cancelled */
2305         case -ECONNRESET:
2306                 break;
2307         case -ENODEV:
2308         case -ESHUTDOWN:
2309                 usbi_dbg("device removed");
2310                 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2311                 goto cancel_remaining;
2312         case -EPIPE:
2313                 usbi_dbg("detected endpoint stall");
2314                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2315                         tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2316                 goto cancel_remaining;
2317         case -EOVERFLOW:
2318                 /* overflow can only ever occur in the last urb */
2319                 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2320                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2321                         tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2322                 goto completed;
2323         case -ETIME:
2324         case -EPROTO:
2325         case -EILSEQ:
2326         case -ECOMM:
2327         case -ENOSR:
2328                 usbi_dbg("low level error %d", urb->status);
2329                 tpriv->reap_action = ERROR;
2330                 goto cancel_remaining;
2331         default:
2332                 usbi_warn(ITRANSFER_CTX(itransfer),
2333                         "unrecognised urb status %d", urb->status);
2334                 tpriv->reap_action = ERROR;
2335                 goto cancel_remaining;
2336         }
2337
2338         /* if we're the last urb or we got less data than requested then we're
2339          * done */
2340         if (urb_idx == tpriv->num_urbs - 1) {
2341                 usbi_dbg("last URB in transfer --> complete!");
2342                 goto completed;
2343         } else if (urb->actual_length < urb->buffer_length) {
2344                 usbi_dbg("short transfer %d/%d --> complete!",
2345                         urb->actual_length, urb->buffer_length);
2346                 if (tpriv->reap_action == NORMAL)
2347                         tpriv->reap_action = COMPLETED_EARLY;
2348         } else
2349                 goto out_unlock;
2350
2351 cancel_remaining:
2352         if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2353                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2354
2355         if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2356                 goto completed;
2357
2358         /* cancel remaining urbs and wait for their completion before
2359          * reporting results */
2360         discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2361
2362 out_unlock:
2363         usbi_mutex_unlock(&itransfer->lock);
2364         return 0;
2365
2366 completed:
2367         free(tpriv->urbs);
2368         tpriv->urbs = NULL;
2369         usbi_mutex_unlock(&itransfer->lock);
2370         return CANCELLED == tpriv->reap_action ?
2371                 usbi_handle_transfer_cancellation(itransfer) :
2372                 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2373 }
2374
2375 static int handle_iso_completion(struct usbi_transfer *itransfer,
2376         struct usbfs_urb *urb)
2377 {
2378         struct libusb_transfer *transfer =
2379                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2380         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2381         int num_urbs = tpriv->num_urbs;
2382         int urb_idx = 0;
2383         int i;
2384         enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2385
2386         usbi_mutex_lock(&itransfer->lock);
2387         for (i = 0; i < num_urbs; i++) {
2388                 if (urb == tpriv->iso_urbs[i]) {
2389                         urb_idx = i + 1;
2390                         break;
2391                 }
2392         }
2393         if (urb_idx == 0) {
2394                 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2395                 usbi_mutex_unlock(&itransfer->lock);
2396                 return LIBUSB_ERROR_NOT_FOUND;
2397         }
2398
2399         usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2400                 urb_idx, num_urbs);
2401
2402         /* copy isochronous results back in */
2403
2404         for (i = 0; i < urb->number_of_packets; i++) {
2405                 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2406                 struct libusb_iso_packet_descriptor *lib_desc =
2407                         &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2408                 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2409                 switch (urb_desc->status) {
2410                 case 0:
2411                         break;
2412                 case -ENOENT: /* cancelled */
2413                 case -ECONNRESET:
2414                         break;
2415                 case -ENODEV:
2416                 case -ESHUTDOWN:
2417                         usbi_dbg("device removed");
2418                         lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2419                         break;
2420                 case -EPIPE:
2421                         usbi_dbg("detected endpoint stall");
2422                         lib_desc->status = LIBUSB_TRANSFER_STALL;
2423                         break;
2424                 case -EOVERFLOW:
2425                         usbi_dbg("overflow error");
2426                         lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2427                         break;
2428                 case -ETIME:
2429                 case -EPROTO:
2430                 case -EILSEQ:
2431                 case -ECOMM:
2432                 case -ENOSR:
2433                 case -EXDEV:
2434                         usbi_dbg("low-level USB error %d", urb_desc->status);
2435                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2436                         break;
2437                 default:
2438                         usbi_warn(TRANSFER_CTX(transfer),
2439                                 "unrecognised urb status %d", urb_desc->status);
2440                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2441                         break;
2442                 }
2443                 lib_desc->actual_length = urb_desc->actual_length;
2444         }
2445
2446         tpriv->num_retired++;
2447
2448         if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2449                 usbi_dbg("CANCEL: urb status %d", urb->status);
2450
2451                 if (tpriv->num_retired == num_urbs) {
2452                         usbi_dbg("CANCEL: last URB handled, reporting");
2453                         free_iso_urbs(tpriv);
2454                         if (tpriv->reap_action == CANCELLED) {
2455                                 usbi_mutex_unlock(&itransfer->lock);
2456                                 return usbi_handle_transfer_cancellation(itransfer);
2457                         } else {
2458                                 usbi_mutex_unlock(&itransfer->lock);
2459                                 return usbi_handle_transfer_completion(itransfer,
2460                                         LIBUSB_TRANSFER_ERROR);
2461                         }
2462                 }
2463                 goto out;
2464         }
2465
2466         switch (urb->status) {
2467         case 0:
2468                 break;
2469         case -ENOENT: /* cancelled */
2470         case -ECONNRESET:
2471                 break;
2472         case -ESHUTDOWN:
2473                 usbi_dbg("device removed");
2474                 status = LIBUSB_TRANSFER_NO_DEVICE;
2475                 break;
2476         default:
2477                 usbi_warn(TRANSFER_CTX(transfer),
2478                         "unrecognised urb status %d", urb->status);
2479                 status = LIBUSB_TRANSFER_ERROR;
2480                 break;
2481         }
2482
2483         /* if we're the last urb then we're done */
2484         if (urb_idx == num_urbs) {
2485                 usbi_dbg("last URB in transfer --> complete!");
2486                 free_iso_urbs(tpriv);
2487                 usbi_mutex_unlock(&itransfer->lock);
2488                 return usbi_handle_transfer_completion(itransfer, status);
2489         }
2490
2491 out:
2492         usbi_mutex_unlock(&itransfer->lock);
2493         return 0;
2494 }
2495
2496 static int handle_control_completion(struct usbi_transfer *itransfer,
2497         struct usbfs_urb *urb)
2498 {
2499         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2500         int status;
2501
2502         usbi_mutex_lock(&itransfer->lock);
2503         usbi_dbg("handling completion status %d", urb->status);
2504
2505         itransfer->transferred += urb->actual_length;
2506
2507         if (tpriv->reap_action == CANCELLED) {
2508                 if (urb->status != 0 && urb->status != -ENOENT)
2509                         usbi_warn(ITRANSFER_CTX(itransfer),
2510                                 "cancel: unrecognised urb status %d", urb->status);
2511                 free(tpriv->urbs);
2512                 tpriv->urbs = NULL;
2513                 usbi_mutex_unlock(&itransfer->lock);
2514                 return usbi_handle_transfer_cancellation(itransfer);
2515         }
2516
2517         switch (urb->status) {
2518         case 0:
2519                 status = LIBUSB_TRANSFER_COMPLETED;
2520                 break;
2521         case -ENOENT: /* cancelled */
2522                 status = LIBUSB_TRANSFER_CANCELLED;
2523                 break;
2524         case -ENODEV:
2525         case -ESHUTDOWN:
2526                 usbi_dbg("device removed");
2527                 status = LIBUSB_TRANSFER_NO_DEVICE;
2528                 break;
2529         case -EPIPE:
2530                 usbi_dbg("unsupported control request");
2531                 status = LIBUSB_TRANSFER_STALL;
2532                 break;
2533         case -EOVERFLOW:
2534                 usbi_dbg("control overflow error");
2535                 status = LIBUSB_TRANSFER_OVERFLOW;
2536                 break;
2537         case -ETIME:
2538         case -EPROTO:
2539         case -EILSEQ:
2540         case -ECOMM:
2541         case -ENOSR:
2542                 usbi_dbg("low-level bus error occurred");
2543                 status = LIBUSB_TRANSFER_ERROR;
2544                 break;
2545         default:
2546                 usbi_warn(ITRANSFER_CTX(itransfer),
2547                         "unrecognised urb status %d", urb->status);
2548                 status = LIBUSB_TRANSFER_ERROR;
2549                 break;
2550         }
2551
2552         free(tpriv->urbs);
2553         tpriv->urbs = NULL;
2554         usbi_mutex_unlock(&itransfer->lock);
2555         return usbi_handle_transfer_completion(itransfer, status);
2556 }
2557
2558 static int reap_for_handle(struct libusb_device_handle *handle)
2559 {
2560         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2561         int r;
2562         struct usbfs_urb *urb;
2563         struct usbi_transfer *itransfer;
2564         struct libusb_transfer *transfer;
2565
2566         r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2567         if (r == -1 && errno == EAGAIN)
2568                 return 1;
2569         if (r < 0) {
2570                 if (errno == ENODEV)
2571                         return LIBUSB_ERROR_NO_DEVICE;
2572
2573                 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2574                         r, errno);
2575                 return LIBUSB_ERROR_IO;
2576         }
2577
2578         itransfer = urb->usercontext;
2579         transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2580
2581         usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2582                 urb->actual_length);
2583
2584         switch (transfer->type) {
2585         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2586                 return handle_iso_completion(itransfer, urb);
2587         case LIBUSB_TRANSFER_TYPE_BULK:
2588         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2589         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2590                 return handle_bulk_completion(itransfer, urb);
2591         case LIBUSB_TRANSFER_TYPE_CONTROL:
2592                 return handle_control_completion(itransfer, urb);
2593         default:
2594                 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2595                         transfer->type);
2596                 return LIBUSB_ERROR_OTHER;
2597         }
2598 }
2599
2600 static int op_handle_events(struct libusb_context *ctx,
2601         struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2602 {
2603         int r;
2604         unsigned int i = 0;
2605
2606         usbi_mutex_lock(&ctx->open_devs_lock);
2607         for (i = 0; i < nfds && num_ready > 0; i++) {
2608                 struct pollfd *pollfd = &fds[i];
2609                 struct libusb_device_handle *handle;
2610                 struct linux_device_handle_priv *hpriv = NULL;
2611
2612                 if (!pollfd->revents)
2613                         continue;
2614
2615                 num_ready--;
2616                 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2617                         hpriv = _device_handle_priv(handle);
2618                         if (hpriv->fd == pollfd->fd)
2619                                 break;
2620                 }
2621
2622                 if (!hpriv || hpriv->fd != pollfd->fd) {
2623                         usbi_err(ctx, "cannot find handle for fd %d",
2624                                  pollfd->fd);
2625                         continue;
2626                 }
2627
2628                 if (pollfd->revents & POLLERR) {
2629                         /* remove the fd from the pollfd set so that it doesn't continuously
2630                          * trigger an event, and flag that it has been removed so op_close()
2631                          * doesn't try to remove it a second time */
2632                         usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2633                         hpriv->fd_removed = 1;
2634
2635                         /* device will still be marked as attached if hotplug monitor thread
2636                          * hasn't processed remove event yet */
2637                         usbi_mutex_static_lock(&linux_hotplug_lock);
2638                         if (handle->dev->attached)
2639                                 linux_device_disconnected(handle->dev->bus_number,
2640                                                 handle->dev->device_address);
2641                         usbi_mutex_static_unlock(&linux_hotplug_lock);
2642
2643                         if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2644                                 do {
2645                                         r = reap_for_handle(handle);
2646                                 } while (r == 0);
2647                         }
2648
2649                         usbi_handle_disconnect(handle);
2650                         continue;
2651                 }
2652
2653                 do {
2654                         r = reap_for_handle(handle);
2655                 } while (r == 0);
2656                 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2657                         continue;
2658                 else if (r < 0)
2659                         goto out;
2660         }
2661
2662         r = 0;
2663 out:
2664         usbi_mutex_unlock(&ctx->open_devs_lock);
2665         return r;
2666 }
2667
2668 static int op_clock_gettime(int clk_id, struct timespec *tp)
2669 {
2670         switch (clk_id) {
2671         case USBI_CLOCK_MONOTONIC:
2672                 return clock_gettime(monotonic_clkid, tp);
2673         case USBI_CLOCK_REALTIME:
2674                 return clock_gettime(CLOCK_REALTIME, tp);
2675         default:
2676                 return LIBUSB_ERROR_INVALID_PARAM;
2677   }
2678 }
2679
2680 #ifdef USBI_TIMERFD_AVAILABLE
2681 static clockid_t op_get_timerfd_clockid(void)
2682 {
2683         return monotonic_clkid;
2684
2685 }
2686 #endif
2687
2688 const struct usbi_os_backend linux_usbfs_backend = {
2689         .name = "Linux usbfs",
2690         .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2691         .init = op_init,
2692         .exit = op_exit,
2693         .get_device_list = NULL,
2694         .hotplug_poll = op_hotplug_poll,
2695         .get_device_descriptor = op_get_device_descriptor,
2696         .get_active_config_descriptor = op_get_active_config_descriptor,
2697         .get_config_descriptor = op_get_config_descriptor,
2698         .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2699
2700         .open = op_open,
2701         .close = op_close,
2702         .get_configuration = op_get_configuration,
2703         .set_configuration = op_set_configuration,
2704         .claim_interface = op_claim_interface,
2705         .release_interface = op_release_interface,
2706
2707         .set_interface_altsetting = op_set_interface,
2708         .clear_halt = op_clear_halt,
2709         .reset_device = op_reset_device,
2710
2711         .alloc_streams = op_alloc_streams,
2712         .free_streams = op_free_streams,
2713
2714         .dev_mem_alloc = op_dev_mem_alloc,
2715         .dev_mem_free = op_dev_mem_free,
2716
2717         .kernel_driver_active = op_kernel_driver_active,
2718         .detach_kernel_driver = op_detach_kernel_driver,
2719         .attach_kernel_driver = op_attach_kernel_driver,
2720
2721         .destroy_device = op_destroy_device,
2722
2723         .submit_transfer = op_submit_transfer,
2724         .cancel_transfer = op_cancel_transfer,
2725         .clear_transfer_priv = op_clear_transfer_priv,
2726
2727         .handle_events = op_handle_events,
2728
2729         .clock_gettime = op_clock_gettime,
2730
2731 #ifdef USBI_TIMERFD_AVAILABLE
2732         .get_timerfd_clockid = op_get_timerfd_clockid,
2733 #endif
2734
2735         .device_priv_size = sizeof(struct linux_device_priv),
2736         .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2737         .transfer_priv_size = sizeof(struct linux_transfer_priv),
2738 };