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