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