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