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