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