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