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