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