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