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