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