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