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