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