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