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