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