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