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