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