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