linux: Use cached config descriptors
[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 /* Protects init_count and serializes scan_devices versus the hotplug-thread */
124 static usbi_mutex_static_t 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(&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(&hotplug_lock);
436
437         return r;
438 }
439
440 static void op_exit(void)
441 {
442         usbi_mutex_static_lock(&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(&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 to next config */
625 static int seek_to_next_config(struct libusb_context *ctx,
626         unsigned char *buffer, int size)
627 {
628         struct libusb_config_descriptor config;
629
630         if (size == 0)
631                 return LIBUSB_ERROR_NOT_FOUND;
632
633         if (size < LIBUSB_DT_CONFIG_SIZE) {
634                 usbi_err(ctx, "short descriptor read %d/%d",
635                          size, LIBUSB_DT_CONFIG_SIZE);
636                 return LIBUSB_ERROR_IO;
637         }
638
639         usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
640
641         if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
642                 usbi_err(ctx, "invalid wTotalLength %d", config.wTotalLength);
643                 return LIBUSB_ERROR_IO;
644         } else if (config.wTotalLength > size) {
645                 usbi_warn(ctx, "short descriptor read %d/%d",
646                           size, config.wTotalLength);
647                 return size;
648         } else
649                 return config.wTotalLength;
650 }
651
652 static int get_config_descriptor_by_value(struct libusb_device *dev,
653         unsigned char **buffer, uint8_t value)
654 {
655         struct libusb_context *ctx = DEVICE_CTX(dev);
656         struct linux_device_priv *priv = _device_priv(dev);
657         unsigned char *descriptors = priv->descriptors;
658         int size = priv->descriptors_len;
659         struct libusb_config_descriptor *config;
660
661         *buffer = NULL;
662
663         /* Skip device header */
664         descriptors += DEVICE_DESC_LENGTH;
665         size -= DEVICE_DESC_LENGTH;
666
667         /* Seek till the config is found, or till "EOF" */
668         while (1) {
669                 int next = seek_to_next_config(ctx, descriptors, size);
670                 if (next < 0)
671                         return next;
672                 config = (struct libusb_config_descriptor *)descriptors;
673                 if (config->bConfigurationValue == value) {
674                         *buffer = descriptors;
675                         return next;
676                 }
677                 size -= next;
678                 descriptors += next;
679         }
680 }
681
682 static int op_get_active_config_descriptor(struct libusb_device *dev,
683         unsigned char *buffer, size_t len, int *host_endian)
684 {
685         int r, config;
686         unsigned char *config_desc;
687
688         /* Unlike the device desc. config descs. are always in raw format */
689         *host_endian = 0;
690
691         if (sysfs_can_relate_devices) {
692                 r = sysfs_get_active_config(dev, &config);
693                 if (r < 0)
694                         return r;
695         } else {
696                 /* Use cached bConfigurationValue */
697                 struct linux_device_priv *priv = _device_priv(dev);
698                 config = priv->active_config;
699         }
700         if (config == -1)
701                 return LIBUSB_ERROR_NOT_FOUND;
702
703         r = get_config_descriptor_by_value(dev, &config_desc, config);
704         if (r < 0)
705                 return r;
706
707         len = MIN(len, r);
708         memcpy(buffer, config_desc, len);
709         return len;
710 }
711
712 static int op_get_config_descriptor(struct libusb_device *dev,
713         uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
714 {
715         struct linux_device_priv *priv = _device_priv(dev);
716         unsigned char *descriptors = priv->descriptors;
717         int i, r, size = priv->descriptors_len;
718
719         /* Unlike the device desc. config descs. are always in raw format */
720         *host_endian = 0;
721
722         /* Skip device header */
723         descriptors += DEVICE_DESC_LENGTH;
724         size -= DEVICE_DESC_LENGTH;
725
726         /* Seek till the config is found, or till "EOF" */
727         for (i = 0; ; i++) {
728                 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
729                 if (r < 0)
730                         return r;
731                 if (i == config_index)
732                         break;
733                 size -= r;
734                 descriptors += r;
735         }
736
737         len = MIN(len, r);
738         memcpy(buffer, descriptors, len);
739         return len;
740 }
741
742 /* send a control message to retrieve active configuration */
743 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
744 {
745         unsigned char active_config = 0;
746         int r;
747
748         struct usbfs_ctrltransfer ctrl = {
749                 .bmRequestType = LIBUSB_ENDPOINT_IN,
750                 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
751                 .wValue = 0,
752                 .wIndex = 0,
753                 .wLength = 1,
754                 .timeout = 1000,
755                 .data = &active_config
756         };
757
758         r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
759         if (r < 0) {
760                 if (errno == ENODEV)
761                         return LIBUSB_ERROR_NO_DEVICE;
762
763                 /* we hit this error path frequently with buggy devices :( */
764                 usbi_warn(DEVICE_CTX(dev),
765                         "get_configuration failed ret=%d errno=%d", r, errno);
766                 return LIBUSB_ERROR_IO;
767         }
768
769         return active_config;
770 }
771
772 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
773         uint8_t devaddr, const char *sysfs_dir)
774 {
775         struct linux_device_priv *priv = _device_priv(dev);
776         struct libusb_context *ctx = DEVICE_CTX(dev);
777         int descriptors_size = 512; /* Begin with a 1024 byte alloc */
778         int fd, speed;
779         ssize_t r;
780
781         dev->bus_number = busnum;
782         dev->device_address = devaddr;
783
784         if (sysfs_dir) {
785                 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
786                 if (!priv->sysfs_dir)
787                         return LIBUSB_ERROR_NO_MEM;
788                 strcpy(priv->sysfs_dir, sysfs_dir);
789
790                 /* Note speed can contain 1.5, in this case __read_sysfs_attr
791                    will stop parsing at the '.' and return 1 */
792                 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
793                 if (speed >= 0) {
794                         switch (speed) {
795                         case     1: dev->speed = LIBUSB_SPEED_LOW; break;
796                         case    12: dev->speed = LIBUSB_SPEED_FULL; break;
797                         case   480: dev->speed = LIBUSB_SPEED_HIGH; break;
798                         case  5000: dev->speed = LIBUSB_SPEED_SUPER; break;
799                         default:
800                                 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
801                         }
802                 }
803         }
804
805         /* cache descriptors in memory */
806         if (sysfs_has_descriptors)
807                 fd = _open_sysfs_attr(dev, "descriptors");
808         else
809                 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
810         if (fd < 0)
811                 return fd;
812
813         do {
814                 descriptors_size *= 2;
815                 priv->descriptors = usbi_reallocf(priv->descriptors,
816                                                   descriptors_size);
817                 if (!priv->descriptors) {
818                         close(fd);
819                         return LIBUSB_ERROR_NO_MEM;
820                 }
821                 /* usbfs has holes in the file */
822                 if (!sysfs_has_descriptors) {
823                         memset(priv->descriptors + priv->descriptors_len,
824                                0, descriptors_size - priv->descriptors_len);
825                 }
826                 r = read(fd, priv->descriptors + priv->descriptors_len,
827                          descriptors_size - priv->descriptors_len);
828                 if (r < 0) {
829                         usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
830                                  fd, errno);
831                         close(fd);
832                         return LIBUSB_ERROR_IO;
833                 }
834                 priv->descriptors_len += r;
835         } while (priv->descriptors_len == descriptors_size);
836         
837         close(fd);
838
839         if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
840                 usbi_err(ctx, "short descriptor read (%d)",
841                          priv->descriptors_len);
842                 return LIBUSB_ERROR_IO;
843         }
844
845         if (sysfs_can_relate_devices)
846                 return LIBUSB_SUCCESS;
847
848         /* cache active config */
849         fd = _get_usbfs_fd(dev, O_RDWR, 1);
850         if (fd < 0) {
851                 /* cannot send a control message to determine the active
852                  * config. just assume the first one is active. */
853                 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
854                                "active configuration descriptor");
855                 if (priv->descriptors_len >=
856                                 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
857                         struct libusb_config_descriptor config;
858                         usbi_parse_descriptor(
859                                 priv->descriptors + DEVICE_DESC_LENGTH,
860                                 "bbwbbbbb", &config, 0);
861                         priv->active_config = config.bConfigurationValue;
862                 } else
863                         priv->active_config = -1; /* No config dt */
864
865                 return LIBUSB_SUCCESS;
866         }
867
868         r = usbfs_get_active_config(dev, fd);
869         if (r > 0) {
870                 priv->active_config = r;
871                 r = LIBUSB_SUCCESS;
872         } else if (r == 0) {
873                 /* some buggy devices have a configuration 0, but we're
874                  * reaching into the corner of a corner case here, so let's
875                  * not support buggy devices in these circumstances.
876                  * stick to the specs: a configuration value of 0 means
877                  * unconfigured. */
878                 usbi_dbg("active cfg 0? assuming unconfigured device");
879                 priv->active_config = -1;
880                 r = LIBUSB_SUCCESS;
881         } else if (r == LIBUSB_ERROR_IO) {
882                 /* buggy devices sometimes fail to report their active config.
883                  * assume unconfigured and continue the probing */
884                 usbi_warn(ctx, "couldn't query active configuration, assuming"
885                                " unconfigured");
886                 priv->active_config = -1;
887                 r = LIBUSB_SUCCESS;
888         } /* else r < 0, just return the error code */
889
890         close(fd);
891         return r;
892 }
893
894 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
895 {
896         struct libusb_context *ctx = DEVICE_CTX(dev);
897         struct libusb_device *it;
898         char *parent_sysfs_dir, *tmp;
899         int ret, add_parent = 1;
900
901         /* XXX -- can we figure out the topology when using usbfs? */
902         if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
903                 /* either using usbfs or finding the parent of a root hub */
904                 return LIBUSB_SUCCESS;
905         }
906
907         parent_sysfs_dir = strdup(sysfs_dir);
908         if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
909             NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
910                 dev->port_number = atoi(tmp + 1);
911                 *tmp = '\0';
912         } else {
913                 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
914                           parent_sysfs_dir);
915                 free (parent_sysfs_dir);
916                 return LIBUSB_SUCCESS;
917         }
918
919         /* is the parent a root hub? */
920         if (NULL == strchr(parent_sysfs_dir, '-')) {
921                 tmp = parent_sysfs_dir;
922                 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
923                 free (tmp);
924                 if (0 > ret) {
925                         return LIBUSB_ERROR_NO_MEM;
926                 }
927         }
928
929 retry:
930         /* find the parent in the context */
931         usbi_mutex_lock(&ctx->usb_devs_lock);
932         list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
933                 struct linux_device_priv *priv = _device_priv(it);
934                 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
935                         dev->parent_dev = libusb_ref_device(it);
936                         break;
937                 }
938         }
939         usbi_mutex_unlock(&ctx->usb_devs_lock);
940
941         if (!dev->parent_dev && add_parent) {
942                 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
943                          parent_sysfs_dir);
944                 sysfs_scan_device(ctx, parent_sysfs_dir);
945                 add_parent = 0;
946                 goto retry;
947         }
948
949         usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
950                  dev->parent_dev, parent_sysfs_dir, dev->port_number);
951
952         free (parent_sysfs_dir);
953
954         return LIBUSB_SUCCESS;
955 }
956
957 int linux_enumerate_device(struct libusb_context *ctx,
958         uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
959 {
960         unsigned long session_id;
961         struct libusb_device *dev;
962         int r = 0;
963
964         /* FIXME: session ID is not guaranteed unique as addresses can wrap and
965          * will be reused. instead we should add a simple sysfs attribute with
966          * a session ID. */
967         session_id = busnum << 8 | devaddr;
968         usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
969                 session_id);
970
971         if (usbi_get_device_by_session_id(ctx, session_id)) {
972                 /* device already exists in the context */
973                 usbi_dbg("session_id %ld already exists", session_id);
974                 return LIBUSB_SUCCESS;
975         }
976
977         usbi_dbg("allocating new device for %d/%d (session %ld)",
978                  busnum, devaddr, session_id);
979         dev = usbi_alloc_device(ctx, session_id);
980         if (!dev)
981                 return LIBUSB_ERROR_NO_MEM;
982
983         r = initialize_device(dev, busnum, devaddr, sysfs_dir);
984         if (r < 0)
985                 goto out;
986         r = usbi_sanitize_device(dev);
987         if (r < 0)
988                 goto out;
989
990         r = linux_get_parent_info(dev, sysfs_dir);
991         if (r < 0)
992                 goto out;
993 out:
994         if (r < 0)
995                 libusb_unref_device(dev);
996         else
997                 usbi_connect_device(dev);
998
999         return r;
1000 }
1001
1002 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1003 {
1004         struct libusb_context *ctx;
1005
1006         usbi_mutex_static_lock(&active_contexts_lock);
1007         usbi_mutex_static_lock(&hotplug_lock);
1008         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1009                 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1010         }
1011         usbi_mutex_static_unlock(&hotplug_lock);
1012         usbi_mutex_static_unlock(&active_contexts_lock);
1013 }
1014
1015 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1016 {
1017         struct libusb_context *ctx;
1018         struct libusb_device *dev;
1019         unsigned long session_id = busnum << 8 | devaddr;
1020
1021         usbi_mutex_static_lock(&active_contexts_lock);
1022         usbi_mutex_static_lock(&hotplug_lock);
1023         list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1024                 dev = usbi_get_device_by_session_id (ctx, session_id);
1025                 if (NULL != dev) {
1026                         usbi_disconnect_device (dev);
1027                 } else {
1028                         usbi_dbg("device not found for session %x", session_id);
1029                 }
1030         }
1031         usbi_mutex_static_unlock(&hotplug_lock);
1032         usbi_mutex_static_unlock(&active_contexts_lock);
1033 }
1034
1035 #if !defined(USE_UDEV)
1036 /* open a bus directory and adds all discovered devices to the context */
1037 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1038 {
1039         DIR *dir;
1040         char dirpath[PATH_MAX];
1041         struct dirent *entry;
1042         int r = LIBUSB_ERROR_IO;
1043
1044         snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1045         usbi_dbg("%s", dirpath);
1046         dir = opendir(dirpath);
1047         if (!dir) {
1048                 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1049                 /* FIXME: should handle valid race conditions like hub unplugged
1050                  * during directory iteration - this is not an error */
1051                 return r;
1052         }
1053
1054         while ((entry = readdir(dir))) {
1055                 int devaddr;
1056
1057                 if (entry->d_name[0] == '.')
1058                         continue;
1059
1060                 devaddr = atoi(entry->d_name);
1061                 if (devaddr == 0) {
1062                         usbi_dbg("unknown dir entry %s", entry->d_name);
1063                         continue;
1064                 }
1065
1066                 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1067                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1068                         continue;
1069                 }
1070
1071                 r = 0;
1072         }
1073
1074         closedir(dir);
1075         return r;
1076 }
1077
1078 static int usbfs_get_device_list(struct libusb_context *ctx)
1079 {
1080         struct dirent *entry;
1081         DIR *buses = opendir(usbfs_path);
1082         int r = 0;
1083
1084         if (!buses) {
1085                 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1086                 return LIBUSB_ERROR_IO;
1087         }
1088
1089         while ((entry = readdir(buses))) {
1090                 int busnum;
1091
1092                 if (entry->d_name[0] == '.')
1093                         continue;
1094
1095                 if (usbdev_names) {
1096                         int devaddr;
1097                         if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1098                                 continue;
1099
1100                         r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1101                         if (r < 0) {
1102                                 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1103                                 continue;
1104                         }
1105                 } else {
1106                         busnum = atoi(entry->d_name);
1107                         if (busnum == 0) {
1108                                 usbi_dbg("unknown dir entry %s", entry->d_name);
1109                                 continue;
1110                         }
1111
1112                         r = usbfs_scan_busdir(ctx, busnum);
1113                         if (r < 0)
1114                                 break;
1115                 }
1116         }
1117
1118         closedir(buses);
1119         return r;
1120
1121 }
1122 #endif
1123
1124 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1125 {
1126         uint8_t busnum, devaddr;
1127         int ret;
1128
1129         ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1130         if (LIBUSB_SUCCESS != ret) {
1131                 return ret;
1132         }
1133
1134         return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1135                 devname);
1136 }
1137
1138 #if !defined(USE_UDEV)
1139 static int sysfs_get_device_list(struct libusb_context *ctx)
1140 {
1141         DIR *devices = opendir(SYSFS_DEVICE_PATH);
1142         struct dirent *entry;
1143         int r = LIBUSB_ERROR_IO;
1144
1145         if (!devices) {
1146                 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1147                 return r;
1148         }
1149
1150         while ((entry = readdir(devices))) {
1151                 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1152                                 || strchr(entry->d_name, ':'))
1153                         continue;
1154
1155                 if (sysfs_scan_device(ctx, entry->d_name)) {
1156                         usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1157                         continue;
1158                 }
1159
1160                 r = 0;
1161         }
1162
1163         closedir(devices);
1164         return r;
1165 }
1166
1167 static int linux_default_scan_devices (struct libusb_context *ctx)
1168 {
1169         /* we can retrieve device list and descriptors from sysfs or usbfs.
1170          * sysfs is preferable, because if we use usbfs we end up resuming
1171          * any autosuspended USB devices. however, sysfs is not available
1172          * everywhere, so we need a usbfs fallback too.
1173          *
1174          * as described in the "sysfs vs usbfs" comment at the top of this
1175          * file, sometimes we have sysfs but not enough information to
1176          * relate sysfs devices to usbfs nodes.  op_init() determines the
1177          * adequacy of sysfs and sets sysfs_can_relate_devices.
1178          */
1179         if (sysfs_can_relate_devices != 0)
1180                 return sysfs_get_device_list(ctx);
1181         else
1182                 return usbfs_get_device_list(ctx);
1183 }
1184 #endif
1185
1186 static int op_open(struct libusb_device_handle *handle)
1187 {
1188         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1189         int r;
1190
1191         hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1192         if (hpriv->fd < 0)
1193                 return hpriv->fd;
1194
1195         r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1196         if (r < 0) {
1197                 if (errno == ENOTTY)
1198                         usbi_dbg("getcap not available");
1199                 else
1200                         usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1201                 hpriv->caps = 0;
1202                 if (supports_flag_zero_packet)
1203                         hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1204                 if (supports_flag_bulk_continuation)
1205                         hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1206         }
1207
1208         return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1209 }
1210
1211 static void op_close(struct libusb_device_handle *dev_handle)
1212 {
1213         int fd = _device_handle_priv(dev_handle)->fd;
1214         usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1215         close(fd);
1216 }
1217
1218 static int op_get_configuration(struct libusb_device_handle *handle,
1219         int *config)
1220 {
1221         int r;
1222         if (sysfs_can_relate_devices != 1)
1223                 return LIBUSB_ERROR_NOT_SUPPORTED;
1224
1225         r = sysfs_get_active_config(handle->dev, config);
1226         if (r < 0)
1227                 return r;
1228
1229         if (*config == -1) {
1230                 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1231                 *config = 0;
1232         }
1233
1234         return 0;
1235 }
1236
1237 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1238 {
1239         struct linux_device_priv *priv = _device_priv(handle->dev);
1240         int fd = _device_handle_priv(handle)->fd;
1241         int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1242         if (r) {
1243                 if (errno == EINVAL)
1244                         return LIBUSB_ERROR_NOT_FOUND;
1245                 else if (errno == EBUSY)
1246                         return LIBUSB_ERROR_BUSY;
1247                 else if (errno == ENODEV)
1248                         return LIBUSB_ERROR_NO_DEVICE;
1249
1250                 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1251                 return LIBUSB_ERROR_OTHER;
1252         }
1253
1254         /* update our cached active config descriptor */
1255         priv->active_config = config;
1256
1257         return LIBUSB_SUCCESS;
1258 }
1259
1260 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1261 {
1262         int fd = _device_handle_priv(handle)->fd;
1263         int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1264         if (r) {
1265                 if (errno == ENOENT)
1266                         return LIBUSB_ERROR_NOT_FOUND;
1267                 else if (errno == EBUSY)
1268                         return LIBUSB_ERROR_BUSY;
1269                 else if (errno == ENODEV)
1270                         return LIBUSB_ERROR_NO_DEVICE;
1271
1272                 usbi_err(HANDLE_CTX(handle),
1273                         "claim interface failed, error %d errno %d", r, errno);
1274                 return LIBUSB_ERROR_OTHER;
1275         }
1276         return 0;
1277 }
1278
1279 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1280 {
1281         int fd = _device_handle_priv(handle)->fd;
1282         int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1283         if (r) {
1284                 if (errno == ENODEV)
1285                         return LIBUSB_ERROR_NO_DEVICE;
1286
1287                 usbi_err(HANDLE_CTX(handle),
1288                         "release interface failed, error %d errno %d", r, errno);
1289                 return LIBUSB_ERROR_OTHER;
1290         }
1291         return 0;
1292 }
1293
1294 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1295         int altsetting)
1296 {
1297         int fd = _device_handle_priv(handle)->fd;
1298         struct usbfs_setinterface setintf;
1299         int r;
1300
1301         setintf.interface = iface;
1302         setintf.altsetting = altsetting;
1303         r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1304         if (r) {
1305                 if (errno == EINVAL)
1306                         return LIBUSB_ERROR_NOT_FOUND;
1307                 else if (errno == ENODEV)
1308                         return LIBUSB_ERROR_NO_DEVICE;
1309
1310                 usbi_err(HANDLE_CTX(handle),
1311                         "setintf failed error %d errno %d", r, errno);
1312                 return LIBUSB_ERROR_OTHER;
1313         }
1314
1315         return 0;
1316 }
1317
1318 static int op_clear_halt(struct libusb_device_handle *handle,
1319         unsigned char endpoint)
1320 {
1321         int fd = _device_handle_priv(handle)->fd;
1322         unsigned int _endpoint = endpoint;
1323         int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1324         if (r) {
1325                 if (errno == ENOENT)
1326                         return LIBUSB_ERROR_NOT_FOUND;
1327                 else if (errno == ENODEV)
1328                         return LIBUSB_ERROR_NO_DEVICE;
1329
1330                 usbi_err(HANDLE_CTX(handle),
1331                         "clear_halt failed error %d errno %d", r, errno);
1332                 return LIBUSB_ERROR_OTHER;
1333         }
1334
1335         return 0;
1336 }
1337
1338 static int op_reset_device(struct libusb_device_handle *handle)
1339 {
1340         int fd = _device_handle_priv(handle)->fd;
1341         int i, r, ret = 0;
1342
1343         /* Doing a device reset will cause the usbfs driver to get unbound
1344            from any interfaces it is bound to. By voluntarily unbinding
1345            the usbfs driver ourself, we stop the kernel from rebinding
1346            the interface after reset (which would end up with the interface
1347            getting bound to the in kernel driver if any). */
1348         for (i = 0; i < USB_MAXINTERFACES; i++) {
1349                 if (handle->claimed_interfaces & (1L << i)) {
1350                         op_release_interface(handle, i);
1351                 }
1352         }
1353
1354         usbi_mutex_lock(&handle->lock);
1355         r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1356         if (r) {
1357                 if (errno == ENODEV) {
1358                         ret = LIBUSB_ERROR_NOT_FOUND;
1359                         goto out;
1360                 }
1361
1362                 usbi_err(HANDLE_CTX(handle),
1363                         "reset failed error %d errno %d", r, errno);
1364                 ret = LIBUSB_ERROR_OTHER;
1365                 goto out;
1366         }
1367
1368         /* And re-claim any interfaces which were claimed before the reset */
1369         for (i = 0; i < USB_MAXINTERFACES; i++) {
1370                 if (handle->claimed_interfaces & (1L << i)) {
1371                         r = op_claim_interface(handle, i);
1372                         if (r) {
1373                                 usbi_warn(HANDLE_CTX(handle),
1374                                         "failed to re-claim interface %d after reset", i);
1375                                 handle->claimed_interfaces &= ~(1L << i);
1376                         }
1377                 }
1378         }
1379 out:
1380         usbi_mutex_unlock(&handle->lock);
1381         return ret;
1382 }
1383
1384 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1385         int interface)
1386 {
1387         int fd = _device_handle_priv(handle)->fd;
1388         struct usbfs_getdriver getdrv;
1389         int r;
1390
1391         getdrv.interface = interface;
1392         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1393         if (r) {
1394                 if (errno == ENODATA)
1395                         return 0;
1396                 else if (errno == ENODEV)
1397                         return LIBUSB_ERROR_NO_DEVICE;
1398
1399                 usbi_err(HANDLE_CTX(handle),
1400                         "get driver failed error %d errno %d", r, errno);
1401                 return LIBUSB_ERROR_OTHER;
1402         }
1403
1404         return 1;
1405 }
1406
1407 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1408         int interface)
1409 {
1410         int fd = _device_handle_priv(handle)->fd;
1411         struct usbfs_ioctl command;
1412         struct usbfs_getdriver getdrv;
1413         int r;
1414
1415         command.ifno = interface;
1416         command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1417         command.data = NULL;
1418
1419         getdrv.interface = interface;
1420         r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1421         if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1422                 return LIBUSB_ERROR_NOT_FOUND;
1423
1424         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1425         if (r) {
1426                 if (errno == ENODATA)
1427                         return LIBUSB_ERROR_NOT_FOUND;
1428                 else if (errno == EINVAL)
1429                         return LIBUSB_ERROR_INVALID_PARAM;
1430                 else if (errno == ENODEV)
1431                         return LIBUSB_ERROR_NO_DEVICE;
1432
1433                 usbi_err(HANDLE_CTX(handle),
1434                         "detach failed error %d errno %d", r, errno);
1435                 return LIBUSB_ERROR_OTHER;
1436         }
1437
1438         return 0;
1439 }
1440
1441 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1442         int interface)
1443 {
1444         int fd = _device_handle_priv(handle)->fd;
1445         struct usbfs_ioctl command;
1446         int r;
1447
1448         command.ifno = interface;
1449         command.ioctl_code = IOCTL_USBFS_CONNECT;
1450         command.data = NULL;
1451
1452         r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1453         if (r < 0) {
1454                 if (errno == ENODATA)
1455                         return LIBUSB_ERROR_NOT_FOUND;
1456                 else if (errno == EINVAL)
1457                         return LIBUSB_ERROR_INVALID_PARAM;
1458                 else if (errno == ENODEV)
1459                         return LIBUSB_ERROR_NO_DEVICE;
1460                 else if (errno == EBUSY)
1461                         return LIBUSB_ERROR_BUSY;
1462
1463                 usbi_err(HANDLE_CTX(handle),
1464                         "attach failed error %d errno %d", r, errno);
1465                 return LIBUSB_ERROR_OTHER;
1466         } else if (r == 0) {
1467                 return LIBUSB_ERROR_NOT_FOUND;
1468         }
1469
1470         return 0;
1471 }
1472
1473 static void op_destroy_device(struct libusb_device *dev)
1474 {
1475         struct linux_device_priv *priv = _device_priv(dev);
1476         if (priv->descriptors)
1477                 free(priv->descriptors);
1478         if (priv->sysfs_dir)
1479                 free(priv->sysfs_dir);
1480 }
1481
1482 /* URBs are discarded in reverse order of submission to avoid races. */
1483 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1484 {
1485         struct libusb_transfer *transfer =
1486                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1487         struct linux_transfer_priv *tpriv =
1488                 usbi_transfer_get_os_priv(itransfer);
1489         struct linux_device_handle_priv *dpriv =
1490                 _device_handle_priv(transfer->dev_handle);
1491         int i, ret = 0;
1492         struct usbfs_urb *urb;
1493
1494         for (i = last_plus_one - 1; i >= first; i--) {
1495                 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1496                         urb = tpriv->iso_urbs[i];
1497                 else
1498                         urb = &tpriv->urbs[i];
1499
1500                 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1501                         continue;
1502
1503                 if (EINVAL == errno) {
1504                         usbi_dbg("URB not found --> assuming ready to be reaped");
1505                         if (i == (last_plus_one - 1))
1506                                 ret = LIBUSB_ERROR_NOT_FOUND;
1507                 } else if (ENODEV == errno) {
1508                         usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1509                         ret = LIBUSB_ERROR_NO_DEVICE;
1510                 } else {
1511                         usbi_warn(TRANSFER_CTX(transfer),
1512                                 "unrecognised discard errno %d", errno);
1513                         ret = LIBUSB_ERROR_OTHER;
1514                 }
1515         }
1516         return ret;
1517 }
1518
1519 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1520 {
1521         int i;
1522         for (i = 0; i < tpriv->num_urbs; i++) {
1523                 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1524                 if (!urb)
1525                         break;
1526                 free(urb);
1527         }
1528
1529         free(tpriv->iso_urbs);
1530         tpriv->iso_urbs = NULL;
1531 }
1532
1533 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1534         unsigned char urb_type)
1535 {
1536         struct libusb_transfer *transfer =
1537                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1538         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1539         struct linux_device_handle_priv *dpriv =
1540                 _device_handle_priv(transfer->dev_handle);
1541         struct usbfs_urb *urbs;
1542         int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1543                 == LIBUSB_ENDPOINT_OUT;
1544         int bulk_buffer_len, use_bulk_continuation;
1545         int r;
1546         int i;
1547         size_t alloc_size;
1548
1549         if (tpriv->urbs)
1550                 return LIBUSB_ERROR_BUSY;
1551
1552         if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1553                         !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1554                 return LIBUSB_ERROR_NOT_SUPPORTED;
1555
1556         /*
1557          * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1558          * around this by splitting large transfers into 16k blocks, and then
1559          * submit all urbs at once. it would be simpler to submit one urb at
1560          * a time, but there is a big performance gain doing it this way.
1561          *
1562          * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1563          * using arbritary large transfers can still be a bad idea though, as
1564          * the kernel needs to allocate physical contiguous memory for this,
1565          * which may fail for large buffers.
1566          *
1567          * The kernel solves this problem by splitting the transfer into
1568          * blocks itself when the host-controller is scatter-gather capable
1569          * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1570          *
1571          * Last, there is the issue of short-transfers when splitting, for
1572          * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1573          * is needed, but this is not always available.
1574          */
1575         if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1576                 /* Good! Just submit everything in one go */
1577                 bulk_buffer_len = transfer->length ? transfer->length : 1;
1578                 use_bulk_continuation = 0;
1579         } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1580                 /* Split the transfers and use bulk-continuation to
1581                    avoid issues with short-transfers */
1582                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1583                 use_bulk_continuation = 1;
1584         } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1585                 /* Don't split, assume the kernel can alloc the buffer
1586                    (otherwise the submit will fail with -ENOMEM) */
1587                 bulk_buffer_len = transfer->length ? transfer->length : 1;
1588                 use_bulk_continuation = 0;
1589         } else {
1590                 /* Bad, splitting without bulk-continuation, short transfers
1591                    which end before the last urb will not work reliable! */
1592                 /* Note we don't warn here as this is "normal" on kernels <
1593                    2.6.32 and not a problem for most applications */
1594                 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1595                 use_bulk_continuation = 0;
1596         }
1597
1598         int num_urbs = transfer->length / bulk_buffer_len;
1599         int last_urb_partial = 0;
1600
1601         if (transfer->length == 0) {
1602                 num_urbs = 1;
1603         } else if ((transfer->length % bulk_buffer_len) > 0) {
1604                 last_urb_partial = 1;
1605                 num_urbs++;
1606         }
1607         usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1608                 transfer->length);
1609         alloc_size = num_urbs * sizeof(struct usbfs_urb);
1610         urbs = calloc(1, alloc_size);
1611         if (!urbs)
1612                 return LIBUSB_ERROR_NO_MEM;
1613         tpriv->urbs = urbs;
1614         tpriv->num_urbs = num_urbs;
1615         tpriv->num_retired = 0;
1616         tpriv->reap_action = NORMAL;
1617         tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1618
1619         for (i = 0; i < num_urbs; i++) {
1620                 struct usbfs_urb *urb = &urbs[i];
1621                 urb->usercontext = itransfer;
1622                 urb->type = urb_type;
1623                 urb->endpoint = transfer->endpoint;
1624                 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1625                 /* don't set the short not ok flag for the last URB */
1626                 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1627                         urb->flags = USBFS_URB_SHORT_NOT_OK;
1628                 if (i == num_urbs - 1 && last_urb_partial)
1629                         urb->buffer_length = transfer->length % bulk_buffer_len;
1630                 else if (transfer->length == 0)
1631                         urb->buffer_length = 0;
1632                 else
1633                         urb->buffer_length = bulk_buffer_len;
1634
1635                 if (i > 0 && use_bulk_continuation)
1636                         urb->flags |= USBFS_URB_BULK_CONTINUATION;
1637
1638                 /* we have already checked that the flag is supported */
1639                 if (is_out && i == num_urbs - 1 &&
1640                     transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1641                         urb->flags |= USBFS_URB_ZERO_PACKET;
1642
1643                 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1644                 if (r < 0) {
1645                         if (errno == ENODEV) {
1646                                 r = LIBUSB_ERROR_NO_DEVICE;
1647                         } else {
1648                                 usbi_err(TRANSFER_CTX(transfer),
1649                                         "submiturb failed error %d errno=%d", r, errno);
1650                                 r = LIBUSB_ERROR_IO;
1651                         }
1652         
1653                         /* if the first URB submission fails, we can simply free up and
1654                          * return failure immediately. */
1655                         if (i == 0) {
1656                                 usbi_dbg("first URB failed, easy peasy");
1657                                 free(urbs);
1658                                 tpriv->urbs = NULL;
1659                                 return r;
1660                         }
1661
1662                         /* if it's not the first URB that failed, the situation is a bit
1663                          * tricky. we may need to discard all previous URBs. there are
1664                          * complications:
1665                          *  - discarding is asynchronous - discarded urbs will be reaped
1666                          *    later. the user must not have freed the transfer when the
1667                          *    discarded URBs are reaped, otherwise libusbx will be using
1668                          *    freed memory.
1669                          *  - the earlier URBs may have completed successfully and we do
1670                          *    not want to throw away any data.
1671                          *  - this URB failing may be no error; EREMOTEIO means that
1672                          *    this transfer simply didn't need all the URBs we submitted
1673                          * so, we report that the transfer was submitted successfully and
1674                          * in case of error we discard all previous URBs. later when
1675                          * the final reap completes we can report error to the user,
1676                          * or success if an earlier URB was completed successfully.
1677                          */
1678                         tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1679
1680                         /* The URBs we haven't submitted yet we count as already
1681                          * retired. */
1682                         tpriv->num_retired += num_urbs - i;
1683
1684                         /* If we completed short then don't try to discard. */
1685                         if (COMPLETED_EARLY == tpriv->reap_action)
1686                                 return 0;
1687
1688                         discard_urbs(itransfer, 0, i);
1689
1690                         usbi_dbg("reporting successful submission but waiting for %d "
1691                                 "discards before reporting error", i);
1692                         return 0;
1693                 }
1694         }
1695
1696         return 0;
1697 }
1698
1699 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1700 {
1701         struct libusb_transfer *transfer =
1702                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1703         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1704         struct linux_device_handle_priv *dpriv =
1705                 _device_handle_priv(transfer->dev_handle);
1706         struct usbfs_urb **urbs;
1707         size_t alloc_size;
1708         int num_packets = transfer->num_iso_packets;
1709         int i;
1710         int this_urb_len = 0;
1711         int num_urbs = 1;
1712         int packet_offset = 0;
1713         unsigned int packet_len;
1714         unsigned char *urb_buffer = transfer->buffer;
1715
1716         if (tpriv->iso_urbs)
1717                 return LIBUSB_ERROR_BUSY;
1718
1719         /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1720          * into smaller units to meet such restriction, then fire off all the
1721          * units at once. it would be simpler if we just fired one unit at a time,
1722          * but there is a big performance gain through doing it this way.
1723          *
1724          * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1725          * using arbritary large transfers is still be a bad idea though, as
1726          * the kernel needs to allocate physical contiguous memory for this,
1727          * which may fail for large buffers.
1728          */
1729
1730         /* calculate how many URBs we need */
1731         for (i = 0; i < num_packets; i++) {
1732                 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1733                 packet_len = transfer->iso_packet_desc[i].length;
1734
1735                 if (packet_len > space_remaining) {
1736                         num_urbs++;
1737                         this_urb_len = packet_len;
1738                 } else {
1739                         this_urb_len += packet_len;
1740                 }
1741         }
1742         usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1743
1744         alloc_size = num_urbs * sizeof(*urbs);
1745         urbs = calloc(1, alloc_size);
1746         if (!urbs)
1747                 return LIBUSB_ERROR_NO_MEM;
1748
1749         tpriv->iso_urbs = urbs;
1750         tpriv->num_urbs = num_urbs;
1751         tpriv->num_retired = 0;
1752         tpriv->reap_action = NORMAL;
1753         tpriv->iso_packet_offset = 0;
1754
1755         /* allocate + initialize each URB with the correct number of packets */
1756         for (i = 0; i < num_urbs; i++) {
1757                 struct usbfs_urb *urb;
1758                 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1759                 int urb_packet_offset = 0;
1760                 unsigned char *urb_buffer_orig = urb_buffer;
1761                 int j;
1762                 int k;
1763
1764                 /* swallow up all the packets we can fit into this URB */
1765                 while (packet_offset < transfer->num_iso_packets) {
1766                         packet_len = transfer->iso_packet_desc[packet_offset].length;
1767                         if (packet_len <= space_remaining_in_urb) {
1768                                 /* throw it in */
1769                                 urb_packet_offset++;
1770                                 packet_offset++;
1771                                 space_remaining_in_urb -= packet_len;
1772                                 urb_buffer += packet_len;
1773                         } else {
1774                                 /* it can't fit, save it for the next URB */
1775                                 break;
1776                         }
1777                 }
1778
1779                 alloc_size = sizeof(*urb)
1780                         + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1781                 urb = calloc(1, alloc_size);
1782                 if (!urb) {
1783                         free_iso_urbs(tpriv);
1784                         return LIBUSB_ERROR_NO_MEM;
1785                 }
1786                 urbs[i] = urb;
1787
1788                 /* populate packet lengths */
1789                 for (j = 0, k = packet_offset - urb_packet_offset;
1790                                 k < packet_offset; k++, j++) {
1791                         packet_len = transfer->iso_packet_desc[k].length;
1792                         urb->iso_frame_desc[j].length = packet_len;
1793                 }
1794
1795                 urb->usercontext = itransfer;
1796                 urb->type = USBFS_URB_TYPE_ISO;
1797                 /* FIXME: interface for non-ASAP data? */
1798                 urb->flags = USBFS_URB_ISO_ASAP;
1799                 urb->endpoint = transfer->endpoint;
1800                 urb->number_of_packets = urb_packet_offset;
1801                 urb->buffer = urb_buffer_orig;
1802         }
1803
1804         /* submit URBs */
1805         for (i = 0; i < num_urbs; i++) {
1806                 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1807                 if (r < 0) {
1808                         if (errno == ENODEV) {
1809                                 r = LIBUSB_ERROR_NO_DEVICE;
1810                         } else {
1811                                 usbi_err(TRANSFER_CTX(transfer),
1812                                         "submiturb failed error %d errno=%d", r, errno);
1813                                 r = LIBUSB_ERROR_IO;
1814                         }
1815
1816                         /* if the first URB submission fails, we can simply free up and
1817                          * return failure immediately. */
1818                         if (i == 0) {
1819                                 usbi_dbg("first URB failed, easy peasy");
1820                                 free_iso_urbs(tpriv);
1821                                 return r;
1822                         }
1823
1824                         /* if it's not the first URB that failed, the situation is a bit
1825                          * tricky. we must discard all previous URBs. there are
1826                          * complications:
1827                          *  - discarding is asynchronous - discarded urbs will be reaped
1828                          *    later. the user must not have freed the transfer when the
1829                          *    discarded URBs are reaped, otherwise libusbx will be using
1830                          *    freed memory.
1831                          *  - the earlier URBs may have completed successfully and we do
1832                          *    not want to throw away any data.
1833                          * so, in this case we discard all the previous URBs BUT we report
1834                          * that the transfer was submitted successfully. then later when
1835                          * the final discard completes we can report error to the user.
1836                          */
1837                         tpriv->reap_action = SUBMIT_FAILED;
1838
1839                         /* The URBs we haven't submitted yet we count as already
1840                          * retired. */
1841                         tpriv->num_retired = num_urbs - i;
1842                         discard_urbs(itransfer, 0, i);
1843
1844                         usbi_dbg("reporting successful submission but waiting for %d "
1845                                 "discards before reporting error", i);
1846                         return 0;
1847                 }
1848         }
1849
1850         return 0;
1851 }
1852
1853 static int submit_control_transfer(struct usbi_transfer *itransfer)
1854 {
1855         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1856         struct libusb_transfer *transfer =
1857                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1858         struct linux_device_handle_priv *dpriv =
1859                 _device_handle_priv(transfer->dev_handle);
1860         struct usbfs_urb *urb;
1861         int r;
1862
1863         if (tpriv->urbs)
1864                 return LIBUSB_ERROR_BUSY;
1865
1866         if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1867                 return LIBUSB_ERROR_INVALID_PARAM;
1868
1869         urb = calloc(1, sizeof(struct usbfs_urb));
1870         if (!urb)
1871                 return LIBUSB_ERROR_NO_MEM;
1872         tpriv->urbs = urb;
1873         tpriv->num_urbs = 1;
1874         tpriv->reap_action = NORMAL;
1875
1876         urb->usercontext = itransfer;
1877         urb->type = USBFS_URB_TYPE_CONTROL;
1878         urb->endpoint = transfer->endpoint;
1879         urb->buffer = transfer->buffer;
1880         urb->buffer_length = transfer->length;
1881
1882         r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1883         if (r < 0) {
1884                 free(urb);
1885                 tpriv->urbs = NULL;
1886                 if (errno == ENODEV)
1887                         return LIBUSB_ERROR_NO_DEVICE;
1888
1889                 usbi_err(TRANSFER_CTX(transfer),
1890                         "submiturb failed error %d errno=%d", r, errno);
1891                 return LIBUSB_ERROR_IO;
1892         }
1893         return 0;
1894 }
1895
1896 static int op_submit_transfer(struct usbi_transfer *itransfer)
1897 {
1898         struct libusb_transfer *transfer =
1899                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1900
1901         switch (transfer->type) {
1902         case LIBUSB_TRANSFER_TYPE_CONTROL:
1903                 return submit_control_transfer(itransfer);
1904         case LIBUSB_TRANSFER_TYPE_BULK:
1905                 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1906         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1907                 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1908         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1909                 return submit_iso_transfer(itransfer);
1910         default:
1911                 usbi_err(TRANSFER_CTX(transfer),
1912                         "unknown endpoint type %d", transfer->type);
1913                 return LIBUSB_ERROR_INVALID_PARAM;
1914         }
1915 }
1916
1917 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1918 {
1919         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1920         struct libusb_transfer *transfer =
1921                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1922
1923         switch (transfer->type) {
1924         case LIBUSB_TRANSFER_TYPE_BULK:
1925                 if (tpriv->reap_action == ERROR)
1926                         break;
1927                 /* else, fall through */
1928         case LIBUSB_TRANSFER_TYPE_CONTROL:
1929         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1930         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1931                 tpriv->reap_action = CANCELLED;
1932                 break;
1933         default:
1934                 usbi_err(TRANSFER_CTX(transfer),
1935                         "unknown endpoint type %d", transfer->type);
1936                 return LIBUSB_ERROR_INVALID_PARAM;
1937         }
1938
1939         if (!tpriv->urbs)
1940                 return LIBUSB_ERROR_NOT_FOUND;
1941
1942         return discard_urbs(itransfer, 0, tpriv->num_urbs);
1943 }
1944
1945 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1946 {
1947         struct libusb_transfer *transfer =
1948                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1949         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1950
1951         /* urbs can be freed also in submit_transfer so lock mutex first */
1952         switch (transfer->type) {
1953         case LIBUSB_TRANSFER_TYPE_CONTROL:
1954         case LIBUSB_TRANSFER_TYPE_BULK:
1955         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1956                 usbi_mutex_lock(&itransfer->lock);
1957                 if (tpriv->urbs)
1958                         free(tpriv->urbs);
1959                 tpriv->urbs = NULL;
1960                 usbi_mutex_unlock(&itransfer->lock);
1961                 break;
1962         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1963                 usbi_mutex_lock(&itransfer->lock);
1964                 if (tpriv->iso_urbs)
1965                         free_iso_urbs(tpriv);
1966                 usbi_mutex_unlock(&itransfer->lock);
1967                 break;
1968         default:
1969                 usbi_err(TRANSFER_CTX(transfer),
1970                         "unknown endpoint type %d", transfer->type);
1971         }
1972 }
1973
1974 static int handle_bulk_completion(struct usbi_transfer *itransfer,
1975         struct usbfs_urb *urb)
1976 {
1977         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1978         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1979         int urb_idx = urb - tpriv->urbs;
1980
1981         usbi_mutex_lock(&itransfer->lock);
1982         usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1983                 urb_idx + 1, tpriv->num_urbs);
1984
1985         tpriv->num_retired++;
1986
1987         if (tpriv->reap_action != NORMAL) {
1988                 /* cancelled, submit_fail, or completed early */
1989                 usbi_dbg("abnormal reap: urb status %d", urb->status);
1990
1991                 /* even though we're in the process of cancelling, it's possible that
1992                  * we may receive some data in these URBs that we don't want to lose.
1993                  * examples:
1994                  * 1. while the kernel is cancelling all the packets that make up an
1995                  *    URB, a few of them might complete. so we get back a successful
1996                  *    cancellation *and* some data.
1997                  * 2. we receive a short URB which marks the early completion condition,
1998                  *    so we start cancelling the remaining URBs. however, we're too
1999                  *    slow and another URB completes (or at least completes partially).
2000                  *    (this can't happen since we always use BULK_CONTINUATION.)
2001                  *
2002                  * When this happens, our objectives are not to lose any "surplus" data,
2003                  * and also to stick it at the end of the previously-received data
2004                  * (closing any holes), so that libusbx reports the total amount of
2005                  * transferred data and presents it in a contiguous chunk.
2006                  */
2007                 if (urb->actual_length > 0) {
2008                         unsigned char *target = transfer->buffer + itransfer->transferred;
2009                         usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2010                         if (urb->buffer != target) {
2011                                 usbi_dbg("moving surplus data from offset %d to offset %d",
2012                                         (unsigned char *) urb->buffer - transfer->buffer,
2013                                         target - transfer->buffer);
2014                                 memmove(target, urb->buffer, urb->actual_length);
2015                         }
2016                         itransfer->transferred += urb->actual_length;
2017                 }
2018
2019                 if (tpriv->num_retired == tpriv->num_urbs) {
2020                         usbi_dbg("abnormal reap: last URB handled, reporting");
2021                         if (tpriv->reap_action != COMPLETED_EARLY &&
2022                             tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2023                                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2024                         goto completed;
2025                 }
2026                 goto out_unlock;
2027         }
2028
2029         itransfer->transferred += urb->actual_length;
2030
2031         /* Many of these errors can occur on *any* urb of a multi-urb
2032          * transfer.  When they do, we tear down the rest of the transfer.
2033          */
2034         switch (urb->status) {
2035         case 0:
2036                 break;
2037         case -EREMOTEIO: /* short transfer */
2038                 break;
2039         case -ENOENT: /* cancelled */
2040         case -ECONNRESET:
2041                 break;
2042         case -ENODEV:
2043         case -ESHUTDOWN:
2044                 usbi_dbg("device removed");
2045                 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2046                 goto cancel_remaining;
2047         case -EPIPE:
2048                 usbi_dbg("detected endpoint stall");
2049                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2050                         tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2051                 goto cancel_remaining;
2052         case -EOVERFLOW:
2053                 /* overflow can only ever occur in the last urb */
2054                 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2055                 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2056                         tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2057                 goto completed;
2058         case -ETIME:
2059         case -EPROTO:
2060         case -EILSEQ:
2061         case -ECOMM:
2062         case -ENOSR:
2063                 usbi_dbg("low level error %d", urb->status);
2064                 tpriv->reap_action = ERROR;
2065                 goto cancel_remaining;
2066         default:
2067                 usbi_warn(ITRANSFER_CTX(itransfer),
2068                         "unrecognised urb status %d", urb->status);
2069                 tpriv->reap_action = ERROR;
2070                 goto cancel_remaining;
2071         }
2072
2073         /* if we're the last urb or we got less data than requested then we're
2074          * done */
2075         if (urb_idx == tpriv->num_urbs - 1) {
2076                 usbi_dbg("last URB in transfer --> complete!");
2077                 goto completed;
2078         } else if (urb->actual_length < urb->buffer_length) {
2079                 usbi_dbg("short transfer %d/%d --> complete!",
2080                         urb->actual_length, urb->buffer_length);
2081                 if (tpriv->reap_action == NORMAL)
2082                         tpriv->reap_action = COMPLETED_EARLY;
2083         } else
2084                 goto out_unlock;
2085
2086 cancel_remaining:
2087         if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2088                 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2089
2090         if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2091                 goto completed;
2092
2093         /* cancel remaining urbs and wait for their completion before
2094          * reporting results */
2095         discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2096
2097 out_unlock:
2098         usbi_mutex_unlock(&itransfer->lock);
2099         return 0;
2100
2101 completed:
2102         free(tpriv->urbs);
2103         tpriv->urbs = NULL;
2104         usbi_mutex_unlock(&itransfer->lock);
2105         return CANCELLED == tpriv->reap_action ?
2106                 usbi_handle_transfer_cancellation(itransfer) :
2107                 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2108 }
2109
2110 static int handle_iso_completion(struct usbi_transfer *itransfer,
2111         struct usbfs_urb *urb)
2112 {
2113         struct libusb_transfer *transfer =
2114                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2115         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2116         int num_urbs = tpriv->num_urbs;
2117         int urb_idx = 0;
2118         int i;
2119         enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2120
2121         usbi_mutex_lock(&itransfer->lock);
2122         for (i = 0; i < num_urbs; i++) {
2123                 if (urb == tpriv->iso_urbs[i]) {
2124                         urb_idx = i + 1;
2125                         break;
2126                 }
2127         }
2128         if (urb_idx == 0) {
2129                 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2130                 usbi_mutex_unlock(&itransfer->lock);
2131                 return LIBUSB_ERROR_NOT_FOUND;
2132         }
2133
2134         usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2135                 urb_idx, num_urbs);
2136
2137         /* copy isochronous results back in */
2138
2139         for (i = 0; i < urb->number_of_packets; i++) {
2140                 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2141                 struct libusb_iso_packet_descriptor *lib_desc =
2142                         &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2143                 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2144                 switch (urb_desc->status) {
2145                 case 0:
2146                         break;
2147                 case -ENOENT: /* cancelled */
2148                 case -ECONNRESET:
2149                         break;
2150                 case -ENODEV:
2151                 case -ESHUTDOWN:
2152                         usbi_dbg("device removed");
2153                         lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2154                         break;
2155                 case -EPIPE:
2156                         usbi_dbg("detected endpoint stall");
2157                         lib_desc->status = LIBUSB_TRANSFER_STALL;
2158                         break;
2159                 case -EOVERFLOW:
2160                         usbi_dbg("overflow error");
2161                         lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2162                         break;
2163                 case -ETIME:
2164                 case -EPROTO:
2165                 case -EILSEQ:
2166                 case -ECOMM:
2167                 case -ENOSR:
2168                 case -EXDEV:
2169                         usbi_dbg("low-level USB error %d", urb_desc->status);
2170                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2171                         break;
2172                 default:
2173                         usbi_warn(TRANSFER_CTX(transfer),
2174                                 "unrecognised urb status %d", urb_desc->status);
2175                         lib_desc->status = LIBUSB_TRANSFER_ERROR;
2176                         break;
2177                 }
2178                 lib_desc->actual_length = urb_desc->actual_length;
2179         }
2180
2181         tpriv->num_retired++;
2182
2183         if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2184                 usbi_dbg("CANCEL: urb status %d", urb->status);
2185
2186                 if (tpriv->num_retired == num_urbs) {
2187                         usbi_dbg("CANCEL: last URB handled, reporting");
2188                         free_iso_urbs(tpriv);
2189                         if (tpriv->reap_action == CANCELLED) {
2190                                 usbi_mutex_unlock(&itransfer->lock);
2191                                 return usbi_handle_transfer_cancellation(itransfer);
2192                         } else {
2193                                 usbi_mutex_unlock(&itransfer->lock);
2194                                 return usbi_handle_transfer_completion(itransfer,
2195                                         LIBUSB_TRANSFER_ERROR);
2196                         }
2197                 }
2198                 goto out;
2199         }
2200
2201         switch (urb->status) {
2202         case 0:
2203                 break;
2204         case -ENOENT: /* cancelled */
2205         case -ECONNRESET:
2206                 break;
2207         case -ESHUTDOWN:
2208                 usbi_dbg("device removed");
2209                 status = LIBUSB_TRANSFER_NO_DEVICE;
2210                 break;
2211         default:
2212                 usbi_warn(TRANSFER_CTX(transfer),
2213                         "unrecognised urb status %d", urb->status);
2214                 status = LIBUSB_TRANSFER_ERROR;
2215                 break;
2216         }
2217
2218         /* if we're the last urb then we're done */
2219         if (urb_idx == num_urbs) {
2220                 usbi_dbg("last URB in transfer --> complete!");
2221                 free_iso_urbs(tpriv);
2222                 usbi_mutex_unlock(&itransfer->lock);
2223                 return usbi_handle_transfer_completion(itransfer, status);
2224         }
2225
2226 out:
2227         usbi_mutex_unlock(&itransfer->lock);
2228         return 0;
2229 }
2230
2231 static int handle_control_completion(struct usbi_transfer *itransfer,
2232         struct usbfs_urb *urb)
2233 {
2234         struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2235         int status;
2236
2237         usbi_mutex_lock(&itransfer->lock);
2238         usbi_dbg("handling completion status %d", urb->status);
2239
2240         itransfer->transferred += urb->actual_length;
2241
2242         if (tpriv->reap_action == CANCELLED) {
2243                 if (urb->status != 0 && urb->status != -ENOENT)
2244                         usbi_warn(ITRANSFER_CTX(itransfer),
2245                                 "cancel: unrecognised urb status %d", urb->status);
2246                 free(tpriv->urbs);
2247                 tpriv->urbs = NULL;
2248                 usbi_mutex_unlock(&itransfer->lock);
2249                 return usbi_handle_transfer_cancellation(itransfer);
2250         }
2251
2252         switch (urb->status) {
2253         case 0:
2254                 status = LIBUSB_TRANSFER_COMPLETED;
2255                 break;
2256         case -ENOENT: /* cancelled */
2257                 status = LIBUSB_TRANSFER_CANCELLED;
2258                 break;
2259         case -ENODEV:
2260         case -ESHUTDOWN:
2261                 usbi_dbg("device removed");
2262                 status = LIBUSB_TRANSFER_NO_DEVICE;
2263                 break;
2264         case -EPIPE:
2265                 usbi_dbg("unsupported control request");
2266                 status = LIBUSB_TRANSFER_STALL;
2267                 break;
2268         case -EOVERFLOW:
2269                 usbi_dbg("control overflow error");
2270                 status = LIBUSB_TRANSFER_OVERFLOW;
2271                 break;
2272         case -ETIME:
2273         case -EPROTO:
2274         case -EILSEQ:
2275         case -ECOMM:
2276         case -ENOSR:
2277                 usbi_dbg("low-level bus error occurred");
2278                 status = LIBUSB_TRANSFER_ERROR;
2279                 break;
2280         default:
2281                 usbi_warn(ITRANSFER_CTX(itransfer),
2282                         "unrecognised urb status %d", urb->status);
2283                 status = LIBUSB_TRANSFER_ERROR;
2284                 break;
2285         }
2286
2287         free(tpriv->urbs);
2288         tpriv->urbs = NULL;
2289         usbi_mutex_unlock(&itransfer->lock);
2290         return usbi_handle_transfer_completion(itransfer, status);
2291 }
2292
2293 static int reap_for_handle(struct libusb_device_handle *handle)
2294 {
2295         struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2296         int r;
2297         struct usbfs_urb *urb;
2298         struct usbi_transfer *itransfer;
2299         struct libusb_transfer *transfer;
2300
2301         r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2302         if (r == -1 && errno == EAGAIN)
2303                 return 1;
2304         if (r < 0) {
2305                 if (errno == ENODEV)
2306                         return LIBUSB_ERROR_NO_DEVICE;
2307
2308                 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2309                         r, errno);
2310                 return LIBUSB_ERROR_IO;
2311         }
2312
2313         itransfer = urb->usercontext;
2314         transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2315
2316         usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2317                 urb->actual_length);
2318
2319         switch (transfer->type) {
2320         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2321                 return handle_iso_completion(itransfer, urb);
2322         case LIBUSB_TRANSFER_TYPE_BULK:
2323         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2324                 return handle_bulk_completion(itransfer, urb);
2325         case LIBUSB_TRANSFER_TYPE_CONTROL:
2326                 return handle_control_completion(itransfer, urb);
2327         default:
2328                 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2329                         transfer->type);
2330                 return LIBUSB_ERROR_OTHER;
2331         }
2332 }
2333
2334 static int op_handle_events(struct libusb_context *ctx,
2335         struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2336 {
2337         int r;
2338         unsigned int i = 0;
2339
2340         usbi_mutex_lock(&ctx->open_devs_lock);
2341         for (i = 0; i < nfds && num_ready > 0; i++) {
2342                 struct pollfd *pollfd = &fds[i];
2343                 struct libusb_device_handle *handle;
2344                 struct linux_device_handle_priv *hpriv = NULL;
2345
2346                 if (!pollfd->revents)
2347                         continue;
2348
2349                 num_ready--;
2350                 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2351                         hpriv = _device_handle_priv(handle);
2352                         if (hpriv->fd == pollfd->fd)
2353                                 break;
2354                 }
2355
2356                 if (pollfd->revents & POLLERR) {
2357                         usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2358                         usbi_handle_disconnect(handle);
2359                         continue;
2360                 }
2361
2362                 do {
2363                         r = reap_for_handle(handle);
2364                 } while (r == 0);
2365                 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2366                         continue;
2367                 else if (r < 0)
2368                         goto out;
2369         }
2370
2371         r = 0;
2372 out:
2373         usbi_mutex_unlock(&ctx->open_devs_lock);
2374         return r;
2375 }
2376
2377 static int op_clock_gettime(int clk_id, struct timespec *tp)
2378 {
2379         switch (clk_id) {
2380         case USBI_CLOCK_MONOTONIC:
2381                 return clock_gettime(monotonic_clkid, tp);
2382         case USBI_CLOCK_REALTIME:
2383                 return clock_gettime(CLOCK_REALTIME, tp);
2384         default:
2385                 return LIBUSB_ERROR_INVALID_PARAM;
2386   }
2387 }
2388
2389 #ifdef USBI_TIMERFD_AVAILABLE
2390 static clockid_t op_get_timerfd_clockid(void)
2391 {
2392         return monotonic_clkid;
2393
2394 }
2395 #endif
2396
2397 const struct usbi_os_backend linux_usbfs_backend = {
2398         .name = "Linux usbfs",
2399         .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2400         .init = op_init,
2401         .exit = op_exit,
2402         .get_device_list = NULL,
2403         .get_device_descriptor = op_get_device_descriptor,
2404         .get_active_config_descriptor = op_get_active_config_descriptor,
2405         .get_config_descriptor = op_get_config_descriptor,
2406
2407         .open = op_open,
2408         .close = op_close,
2409         .get_configuration = op_get_configuration,
2410         .set_configuration = op_set_configuration,
2411         .claim_interface = op_claim_interface,
2412         .release_interface = op_release_interface,
2413
2414         .set_interface_altsetting = op_set_interface,
2415         .clear_halt = op_clear_halt,
2416         .reset_device = op_reset_device,
2417
2418         .kernel_driver_active = op_kernel_driver_active,
2419         .detach_kernel_driver = op_detach_kernel_driver,
2420         .attach_kernel_driver = op_attach_kernel_driver,
2421
2422         .destroy_device = op_destroy_device,
2423
2424         .submit_transfer = op_submit_transfer,
2425         .cancel_transfer = op_cancel_transfer,
2426         .clear_transfer_priv = op_clear_transfer_priv,
2427
2428         .handle_events = op_handle_events,
2429
2430         .clock_gettime = op_clock_gettime,
2431
2432 #ifdef USBI_TIMERFD_AVAILABLE
2433         .get_timerfd_clockid = op_get_timerfd_clockid,
2434 #endif
2435
2436         .device_priv_size = sizeof(struct linux_device_priv),
2437         .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2438         .transfer_priv_size = sizeof(struct linux_transfer_priv),
2439         .add_iso_packet_size = 0,
2440 };