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