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