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