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