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