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