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