xref: /aosp_15_r20/external/libusb/libusb/os/linux_usbfs.c (revision 86b64dcb59b3a0b37502ecd56e119234366a6f7e)
1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
2 /*
3  * Linux usbfs backend for libusb
4  * Copyright © 2007-2009 Daniel Drake <[email protected]>
5  * Copyright © 2001 Johannes Erdfelt <[email protected]>
6  * Copyright © 2013 Nathan Hjelm <[email protected]>
7  * Copyright © 2012-2013 Hans de Goede <[email protected]>
8  * Copyright © 2020 Chris Dickens <[email protected]>
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 (buf == endptr || 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, *end;
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 		const char *start = tmp + 1;
1052 		long port_number = strtol(start, &end, 10);
1053 		if (port_number < 0 || port_number > INT_MAX || start == end || '\0' != *end) {
1054 			usbi_warn(ctx, "Can not parse sysfs_dir: %s, unexpected parent info",
1055 				parent_sysfs_dir);
1056 			free(parent_sysfs_dir);
1057 			return LIBUSB_ERROR_OTHER;
1058 		} else {
1059 			dev->port_number = (int)port_number;
1060 		}
1061 		*tmp = '\0';
1062 	} else {
1063 		usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1064 			  parent_sysfs_dir);
1065 		free(parent_sysfs_dir);
1066 		return LIBUSB_SUCCESS;
1067 	}
1068 
1069 	/* is the parent a root hub? */
1070 	if (!strchr(parent_sysfs_dir, '-')) {
1071 		tmp = parent_sysfs_dir;
1072 		ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
1073 		free(tmp);
1074 		if (ret < 0)
1075 			return LIBUSB_ERROR_NO_MEM;
1076 	}
1077 
1078 retry:
1079 	/* find the parent in the context */
1080 	usbi_mutex_lock(&ctx->usb_devs_lock);
1081 	for_each_device(ctx, it) {
1082 		struct linux_device_priv *priv = usbi_get_device_priv(it);
1083 
1084 		if (priv->sysfs_dir) {
1085 			if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
1086 				dev->parent_dev = libusb_ref_device(it);
1087 				break;
1088 			}
1089 		}
1090 	}
1091 	usbi_mutex_unlock(&ctx->usb_devs_lock);
1092 
1093 	if (!dev->parent_dev && add_parent) {
1094 		usbi_dbg(ctx, "parent_dev %s not enumerated yet, enumerating now",
1095 			 parent_sysfs_dir);
1096 		sysfs_scan_device(ctx, parent_sysfs_dir);
1097 		add_parent = 0;
1098 		goto retry;
1099 	}
1100 
1101 	usbi_dbg(ctx, "dev %p (%s) has parent %p (%s) port %u",
1102 		 (void *) dev, sysfs_dir, (void *) dev->parent_dev,
1103 		 parent_sysfs_dir, dev->port_number);
1104 
1105 	free(parent_sysfs_dir);
1106 
1107 	return LIBUSB_SUCCESS;
1108 }
1109 
linux_enumerate_device(struct libusb_context * ctx,uint8_t busnum,uint8_t devaddr,const char * sysfs_dir)1110 int linux_enumerate_device(struct libusb_context *ctx,
1111 	uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1112 {
1113 	unsigned long session_id;
1114 	struct libusb_device *dev;
1115 	int r;
1116 
1117 	/* FIXME: session ID is not guaranteed unique as addresses can wrap and
1118 	 * will be reused. instead we should add a simple sysfs attribute with
1119 	 * a session ID. */
1120 	session_id = busnum << 8 | devaddr;
1121 	usbi_dbg(ctx, "busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1122 
1123 	dev = usbi_get_device_by_session_id(ctx, session_id);
1124 	if (dev) {
1125 		/* device already exists in the context */
1126 		usbi_dbg(ctx, "session_id %lu already exists", session_id);
1127 		libusb_unref_device(dev);
1128 		return LIBUSB_SUCCESS;
1129 	}
1130 
1131 	usbi_dbg(ctx, "allocating new device for %u/%u (session %lu)",
1132 		 busnum, devaddr, session_id);
1133 	dev = usbi_alloc_device(ctx, session_id);
1134 	if (!dev)
1135 		return LIBUSB_ERROR_NO_MEM;
1136 
1137 	r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1138 	if (r < 0)
1139 		goto out;
1140 	r = usbi_sanitize_device(dev);
1141 	if (r < 0)
1142 		goto out;
1143 
1144 	r = linux_get_parent_info(dev, sysfs_dir);
1145 	if (r < 0)
1146 		goto out;
1147 out:
1148 	if (r < 0)
1149 		libusb_unref_device(dev);
1150 	else
1151 		usbi_connect_device(dev);
1152 
1153 	return r;
1154 }
1155 
linux_hotplug_enumerate(uint8_t busnum,uint8_t devaddr,const char * sys_name)1156 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1157 {
1158 	struct libusb_context *ctx;
1159 
1160 	usbi_mutex_static_lock(&active_contexts_lock);
1161 	for_each_context(ctx) {
1162 		linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1163 	}
1164 	usbi_mutex_static_unlock(&active_contexts_lock);
1165 }
1166 
linux_device_disconnected(uint8_t busnum,uint8_t devaddr)1167 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1168 {
1169 	struct libusb_context *ctx;
1170 	struct libusb_device *dev;
1171 	unsigned long session_id = busnum << 8 | devaddr;
1172 
1173 	usbi_mutex_static_lock(&active_contexts_lock);
1174 	for_each_context(ctx) {
1175 		dev = usbi_get_device_by_session_id(ctx, session_id);
1176 		if (dev) {
1177 			usbi_disconnect_device(dev);
1178 			libusb_unref_device(dev);
1179 		} else {
1180 			usbi_dbg(ctx, "device not found for session %lx", session_id);
1181 		}
1182 	}
1183 	usbi_mutex_static_unlock(&active_contexts_lock);
1184 }
1185 
1186 #if !defined(HAVE_LIBUDEV)
parse_u8(const char * str,uint8_t * val_p)1187 static int parse_u8(const char *str, uint8_t *val_p)
1188 {
1189 	char *endptr;
1190 	long num;
1191 
1192 	errno = 0;
1193 	num = strtol(str, &endptr, 10);
1194 	if (num < 0 || num > UINT8_MAX || errno)
1195 		return 0;
1196 	if (endptr == str || *endptr != '\0')
1197 		return 0;
1198 
1199 	*val_p = (uint8_t)num;
1200 	return 1;
1201 }
1202 
1203 /* open a bus directory and adds all discovered devices to the context */
usbfs_scan_busdir(struct libusb_context * ctx,uint8_t busnum)1204 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1205 {
1206 	DIR *dir;
1207 	char dirpath[20];
1208 	struct dirent *entry;
1209 	int r = LIBUSB_ERROR_IO;
1210 
1211 	snprintf(dirpath, sizeof(dirpath), USB_DEVTMPFS_PATH "/%03u", busnum);
1212 	usbi_dbg(ctx, "%s", dirpath);
1213 	dir = opendir(dirpath);
1214 	if (!dir) {
1215 		usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1216 		/* FIXME: should handle valid race conditions like hub unplugged
1217 		 * during directory iteration - this is not an error */
1218 		return r;
1219 	}
1220 
1221 	while ((entry = readdir(dir))) {
1222 		uint8_t devaddr;
1223 
1224 		if (entry->d_name[0] == '.')
1225 			continue;
1226 
1227 		if (!parse_u8(entry->d_name, &devaddr)) {
1228 			usbi_dbg(ctx, "unknown dir entry %s", entry->d_name);
1229 			continue;
1230 		}
1231 
1232 		if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1233 			usbi_dbg(ctx, "failed to enumerate dir entry %s", entry->d_name);
1234 			continue;
1235 		}
1236 
1237 		r = 0;
1238 	}
1239 
1240 	closedir(dir);
1241 	return r;
1242 }
1243 
usbfs_get_device_list(struct libusb_context * ctx)1244 static int usbfs_get_device_list(struct libusb_context *ctx)
1245 {
1246 	struct dirent *entry;
1247 	DIR *buses;
1248 	uint8_t busnum, devaddr;
1249 	int r = 0;
1250 
1251 	if (usbdev_names)
1252 		buses = opendir(USBDEV_PATH);
1253 	else
1254 		buses = opendir(USB_DEVTMPFS_PATH);
1255 
1256 	if (!buses) {
1257 		usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1258 		return LIBUSB_ERROR_IO;
1259 	}
1260 
1261 	while ((entry = readdir(buses))) {
1262 		if (entry->d_name[0] == '.')
1263 			continue;
1264 
1265 		if (usbdev_names) {
1266 			if (!is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1267 				continue;
1268 
1269 			r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1270 			if (r < 0) {
1271 				usbi_dbg(ctx, "failed to enumerate dir entry %s", entry->d_name);
1272 				continue;
1273 			}
1274 		} else {
1275 			if (!parse_u8(entry->d_name, &busnum)) {
1276 				usbi_dbg(ctx, "unknown dir entry %s", entry->d_name);
1277 				continue;
1278 			}
1279 
1280 			r = usbfs_scan_busdir(ctx, busnum);
1281 			if (r < 0)
1282 				break;
1283 		}
1284 	}
1285 
1286 	closedir(buses);
1287 	return r;
1288 
1289 }
1290 
sysfs_get_device_list(struct libusb_context * ctx)1291 static int sysfs_get_device_list(struct libusb_context *ctx)
1292 {
1293 	DIR *devices = opendir(SYSFS_DEVICE_PATH);
1294 	struct dirent *entry;
1295 	int num_devices = 0;
1296 	int num_enumerated = 0;
1297 
1298 	if (!devices) {
1299 		usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1300 		return LIBUSB_ERROR_IO;
1301 	}
1302 
1303 	while ((entry = readdir(devices))) {
1304 		if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1305 		    || strchr(entry->d_name, ':'))
1306 			continue;
1307 
1308 		num_devices++;
1309 
1310 		if (sysfs_scan_device(ctx, entry->d_name)) {
1311 			usbi_dbg(ctx, "failed to enumerate dir entry %s", entry->d_name);
1312 			continue;
1313 		}
1314 
1315 		num_enumerated++;
1316 	}
1317 
1318 	closedir(devices);
1319 
1320 	/* successful if at least one device was enumerated or no devices were found */
1321 	if (num_enumerated || !num_devices)
1322 		return LIBUSB_SUCCESS;
1323 	else
1324 		return LIBUSB_ERROR_IO;
1325 }
1326 
linux_default_scan_devices(struct libusb_context * ctx)1327 static int linux_default_scan_devices(struct libusb_context *ctx)
1328 {
1329 	/* we can retrieve device list and descriptors from sysfs or usbfs.
1330 	 * sysfs is preferable, because if we use usbfs we end up resuming
1331 	 * any autosuspended USB devices. however, sysfs is not available
1332 	 * everywhere, so we need a usbfs fallback too.
1333 	 */
1334 	if (sysfs_available)
1335 		return sysfs_get_device_list(ctx);
1336 	else
1337 		return usbfs_get_device_list(ctx);
1338 }
1339 #endif
1340 
initialize_handle(struct libusb_device_handle * handle,int fd)1341 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1342 {
1343 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1344 	int r;
1345 
1346 	hpriv->fd = fd;
1347 
1348 	r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1349 	if (r < 0) {
1350 		if (errno == ENOTTY)
1351 			usbi_dbg(HANDLE_CTX(handle), "getcap not available");
1352 		else
1353 			usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1354 		hpriv->caps = USBFS_CAP_BULK_CONTINUATION;
1355 	}
1356 
1357 	return usbi_add_event_source(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1358 }
1359 
op_wrap_sys_device(struct libusb_context * ctx,struct libusb_device_handle * handle,intptr_t sys_dev)1360 static int op_wrap_sys_device(struct libusb_context *ctx,
1361 	struct libusb_device_handle *handle, intptr_t sys_dev)
1362 {
1363 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1364 	int fd = (int)sys_dev;
1365 	uint8_t busnum, devaddr;
1366 	struct usbfs_connectinfo ci;
1367 	struct libusb_device *dev;
1368 	int r;
1369 
1370 	r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1371 	if (r < 0) {
1372 		r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1373 		if (r < 0) {
1374 			usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1375 			return LIBUSB_ERROR_IO;
1376 		}
1377 		/* There is no ioctl to get the bus number. We choose 0 here
1378 		 * as linux starts numbering buses from 1. */
1379 		busnum = 0;
1380 		devaddr = ci.devnum;
1381 	}
1382 
1383 	/* Session id is unused as we do not add the device to the list of
1384 	 * connected devices. */
1385 	usbi_dbg(ctx, "allocating new device for fd %d", fd);
1386 	dev = usbi_alloc_device(ctx, 0);
1387 	if (!dev)
1388 		return LIBUSB_ERROR_NO_MEM;
1389 
1390 	r = initialize_device(dev, busnum, devaddr, NULL, fd);
1391 	if (r < 0)
1392 		goto out;
1393 	r = usbi_sanitize_device(dev);
1394 	if (r < 0)
1395 		goto out;
1396 	/* Consider the device as connected, but do not add it to the managed
1397 	 * device list. */
1398 	usbi_atomic_store(&dev->attached, 1);
1399 	handle->dev = dev;
1400 
1401 	r = initialize_handle(handle, fd);
1402 	hpriv->fd_keep = 1;
1403 
1404 out:
1405 	if (r < 0)
1406 		libusb_unref_device(dev);
1407 	return r;
1408 }
1409 
op_open(struct libusb_device_handle * handle)1410 static int op_open(struct libusb_device_handle *handle)
1411 {
1412 	int fd, r;
1413 
1414 	fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1415 	if (fd < 0) {
1416 		if (fd == LIBUSB_ERROR_NO_DEVICE) {
1417 			/* device will still be marked as attached if hotplug monitor thread
1418 			 * hasn't processed remove event yet */
1419 			usbi_mutex_static_lock(&linux_hotplug_lock);
1420 			if (usbi_atomic_load(&handle->dev->attached)) {
1421 				usbi_dbg(HANDLE_CTX(handle), "open failed with no device, but device still attached");
1422 				linux_device_disconnected(handle->dev->bus_number,
1423 							  handle->dev->device_address);
1424 			}
1425 			usbi_mutex_static_unlock(&linux_hotplug_lock);
1426 		}
1427 		return fd;
1428 	}
1429 
1430 	r = initialize_handle(handle, fd);
1431 	if (r < 0)
1432 		close(fd);
1433 
1434 	return r;
1435 }
1436 
op_close(struct libusb_device_handle * dev_handle)1437 static void op_close(struct libusb_device_handle *dev_handle)
1438 {
1439 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(dev_handle);
1440 
1441 	/* fd may have already been removed by POLLERR condition in op_handle_events() */
1442 	if (!hpriv->fd_removed)
1443 		usbi_remove_event_source(HANDLE_CTX(dev_handle), hpriv->fd);
1444 	if (!hpriv->fd_keep)
1445 		close(hpriv->fd);
1446 }
1447 
op_get_configuration(struct libusb_device_handle * handle,uint8_t * config)1448 static int op_get_configuration(struct libusb_device_handle *handle,
1449 	uint8_t *config)
1450 {
1451 	struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1452 	int active_config = -1; /* to please compiler */
1453 	int r;
1454 
1455 	if (priv->sysfs_dir) {
1456 		r = sysfs_get_active_config(handle->dev, &active_config);
1457 	} else {
1458 		struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1459 
1460 		r = usbfs_get_active_config(handle->dev, hpriv->fd);
1461 		if (r == LIBUSB_SUCCESS)
1462 			active_config = priv->active_config;
1463 	}
1464 	if (r < 0)
1465 		return r;
1466 
1467 	if (active_config == -1) {
1468 		usbi_warn(HANDLE_CTX(handle), "device unconfigured");
1469 		active_config = 0;
1470 	}
1471 
1472 	*config = (uint8_t)active_config;
1473 
1474 	return 0;
1475 }
1476 
op_set_configuration(struct libusb_device_handle * handle,int config)1477 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1478 {
1479 	struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1480 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1481 	int fd = hpriv->fd;
1482 	int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1483 
1484 	if (r < 0) {
1485 		if (errno == EINVAL)
1486 			return LIBUSB_ERROR_NOT_FOUND;
1487 		else if (errno == EBUSY)
1488 			return LIBUSB_ERROR_BUSY;
1489 		else if (errno == ENODEV)
1490 			return LIBUSB_ERROR_NO_DEVICE;
1491 
1492 		usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1493 		return LIBUSB_ERROR_OTHER;
1494 	}
1495 
1496 	/* if necessary, update our cached active config descriptor */
1497 	if (!priv->sysfs_dir) {
1498 		if (config == 0 && !dev_has_config0(handle->dev))
1499 			config = -1;
1500 
1501 		priv->active_config = config;
1502 	}
1503 
1504 	return LIBUSB_SUCCESS;
1505 }
1506 
claim_interface(struct libusb_device_handle * handle,unsigned int iface)1507 static int claim_interface(struct libusb_device_handle *handle, unsigned int iface)
1508 {
1509 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1510 	int fd = hpriv->fd;
1511 	int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1512 
1513 	if (r < 0) {
1514 		if (errno == ENOENT)
1515 			return LIBUSB_ERROR_NOT_FOUND;
1516 		else if (errno == EBUSY)
1517 			return LIBUSB_ERROR_BUSY;
1518 		else if (errno == ENODEV)
1519 			return LIBUSB_ERROR_NO_DEVICE;
1520 
1521 		usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1522 		return LIBUSB_ERROR_OTHER;
1523 	}
1524 	return 0;
1525 }
1526 
release_interface(struct libusb_device_handle * handle,unsigned int iface)1527 static int release_interface(struct libusb_device_handle *handle, unsigned int iface)
1528 {
1529 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1530 	int fd = hpriv->fd;
1531 	int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1532 
1533 	if (r < 0) {
1534 		if (errno == ENODEV)
1535 			return LIBUSB_ERROR_NO_DEVICE;
1536 
1537 		usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1538 		return LIBUSB_ERROR_OTHER;
1539 	}
1540 	return 0;
1541 }
1542 
op_set_interface(struct libusb_device_handle * handle,uint8_t interface,uint8_t altsetting)1543 static int op_set_interface(struct libusb_device_handle *handle, uint8_t interface,
1544 	uint8_t altsetting)
1545 {
1546 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1547 	int fd = hpriv->fd;
1548 	struct usbfs_setinterface setintf;
1549 	int r;
1550 
1551 	setintf.interface = interface;
1552 	setintf.altsetting = altsetting;
1553 	r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1554 	if (r < 0) {
1555 		if (errno == EINVAL)
1556 			return LIBUSB_ERROR_NOT_FOUND;
1557 		else if (errno == ENODEV)
1558 			return LIBUSB_ERROR_NO_DEVICE;
1559 
1560 		usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1561 		return LIBUSB_ERROR_OTHER;
1562 	}
1563 
1564 	return 0;
1565 }
1566 
op_clear_halt(struct libusb_device_handle * handle,unsigned char endpoint)1567 static int op_clear_halt(struct libusb_device_handle *handle,
1568 	unsigned char endpoint)
1569 {
1570 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1571 	int fd = hpriv->fd;
1572 	unsigned int _endpoint = endpoint;
1573 	int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1574 
1575 	if (r < 0) {
1576 		if (errno == ENOENT)
1577 			return LIBUSB_ERROR_NOT_FOUND;
1578 		else if (errno == ENODEV)
1579 			return LIBUSB_ERROR_NO_DEVICE;
1580 
1581 		usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1582 		return LIBUSB_ERROR_OTHER;
1583 	}
1584 
1585 	return 0;
1586 }
1587 
op_reset_device(struct libusb_device_handle * handle)1588 static int op_reset_device(struct libusb_device_handle *handle)
1589 {
1590 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1591 	int fd = hpriv->fd;
1592 	int r, ret = 0;
1593 	uint8_t i;
1594 
1595 	/* Doing a device reset will cause the usbfs driver to get unbound
1596 	 * from any interfaces it is bound to. By voluntarily unbinding
1597 	 * the usbfs driver ourself, we stop the kernel from rebinding
1598 	 * the interface after reset (which would end up with the interface
1599 	 * getting bound to the in kernel driver if any). */
1600 	for (i = 0; i < USB_MAXINTERFACES; i++) {
1601 		if (handle->claimed_interfaces & (1UL << i))
1602 			release_interface(handle, i);
1603 	}
1604 
1605 	usbi_mutex_lock(&handle->lock);
1606 	r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1607 	if (r < 0) {
1608 		if (errno == ENODEV) {
1609 			ret = LIBUSB_ERROR_NOT_FOUND;
1610 			goto out;
1611 		}
1612 
1613 		usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1614 		ret = LIBUSB_ERROR_OTHER;
1615 		goto out;
1616 	}
1617 
1618 	/* And re-claim any interfaces which were claimed before the reset */
1619 	for (i = 0; i < USB_MAXINTERFACES; i++) {
1620 		if (!(handle->claimed_interfaces & (1UL << i)))
1621 			continue;
1622 		/*
1623 		 * A driver may have completed modprobing during
1624 		 * IOCTL_USBFS_RESET, and bound itself as soon as
1625 		 * IOCTL_USBFS_RESET released the device lock
1626 		 */
1627 		r = detach_kernel_driver_and_claim(handle, i);
1628 		if (r) {
1629 			usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %u after reset: %s",
1630 				  i, libusb_error_name(r));
1631 			handle->claimed_interfaces &= ~(1UL << i);
1632 			ret = LIBUSB_ERROR_NOT_FOUND;
1633 		}
1634 	}
1635 out:
1636 	usbi_mutex_unlock(&handle->lock);
1637 	return ret;
1638 }
1639 
do_streams_ioctl(struct libusb_device_handle * handle,unsigned long req,uint32_t num_streams,unsigned char * endpoints,int num_endpoints)1640 static int do_streams_ioctl(struct libusb_device_handle *handle,
1641 	unsigned long req, uint32_t num_streams, unsigned char *endpoints,
1642 	int num_endpoints)
1643 {
1644 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1645 	int r, fd = hpriv->fd;
1646 	struct usbfs_streams *streams;
1647 
1648 	if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1649 		return LIBUSB_ERROR_INVALID_PARAM;
1650 
1651 	streams = malloc(sizeof(*streams) + num_endpoints);
1652 	if (!streams)
1653 		return LIBUSB_ERROR_NO_MEM;
1654 
1655 	streams->num_streams = num_streams;
1656 	streams->num_eps = num_endpoints;
1657 	memcpy(streams->eps, endpoints, num_endpoints);
1658 
1659 	r = ioctl(fd, req, streams);
1660 
1661 	free(streams);
1662 
1663 	if (r < 0) {
1664 		if (errno == ENOTTY)
1665 			return LIBUSB_ERROR_NOT_SUPPORTED;
1666 		else if (errno == EINVAL)
1667 			return LIBUSB_ERROR_INVALID_PARAM;
1668 		else if (errno == ENODEV)
1669 			return LIBUSB_ERROR_NO_DEVICE;
1670 
1671 		usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1672 		return LIBUSB_ERROR_OTHER;
1673 	}
1674 	return r;
1675 }
1676 
op_alloc_streams(struct libusb_device_handle * handle,uint32_t num_streams,unsigned char * endpoints,int num_endpoints)1677 static int op_alloc_streams(struct libusb_device_handle *handle,
1678 	uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1679 {
1680 	return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1681 				num_streams, endpoints, num_endpoints);
1682 }
1683 
op_free_streams(struct libusb_device_handle * handle,unsigned char * endpoints,int num_endpoints)1684 static int op_free_streams(struct libusb_device_handle *handle,
1685 		unsigned char *endpoints, int num_endpoints)
1686 {
1687 	return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1688 				endpoints, num_endpoints);
1689 }
1690 
op_dev_mem_alloc(struct libusb_device_handle * handle,size_t len)1691 static void *op_dev_mem_alloc(struct libusb_device_handle *handle, size_t len)
1692 {
1693 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1694 	void *buffer;
1695 
1696 	buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1697 	if (buffer == MAP_FAILED) {
1698 		usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1699 		return NULL;
1700 	}
1701 	return buffer;
1702 }
1703 
op_dev_mem_free(struct libusb_device_handle * handle,void * buffer,size_t len)1704 static int op_dev_mem_free(struct libusb_device_handle *handle, void *buffer,
1705 	size_t len)
1706 {
1707 	if (munmap(buffer, len) != 0) {
1708 		usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1709 		return LIBUSB_ERROR_OTHER;
1710 	} else {
1711 		return LIBUSB_SUCCESS;
1712 	}
1713 }
1714 
op_kernel_driver_active(struct libusb_device_handle * handle,uint8_t interface)1715 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1716 	uint8_t interface)
1717 {
1718 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1719 	int fd = hpriv->fd;
1720 	struct usbfs_getdriver getdrv;
1721 	int r;
1722 
1723 	getdrv.interface = interface;
1724 	r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1725 	if (r < 0) {
1726 		if (errno == ENODATA)
1727 			return 0;
1728 		else if (errno == ENODEV)
1729 			return LIBUSB_ERROR_NO_DEVICE;
1730 
1731 		usbi_err(HANDLE_CTX(handle), "get driver failed, errno=%d", errno);
1732 		return LIBUSB_ERROR_OTHER;
1733 	}
1734 
1735 	return strcmp(getdrv.driver, "usbfs") != 0;
1736 }
1737 
op_detach_kernel_driver(struct libusb_device_handle * handle,uint8_t interface)1738 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1739 	uint8_t interface)
1740 {
1741 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1742 	int fd = hpriv->fd;
1743 	struct usbfs_ioctl command;
1744 	struct usbfs_getdriver getdrv;
1745 	int r;
1746 
1747 	command.ifno = interface;
1748 	command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1749 	command.data = NULL;
1750 
1751 	getdrv.interface = interface;
1752 	r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1753 	if (r == 0 && !strcmp(getdrv.driver, "usbfs"))
1754 		return LIBUSB_ERROR_NOT_FOUND;
1755 
1756 	r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1757 	if (r < 0) {
1758 		if (errno == ENODATA)
1759 			return LIBUSB_ERROR_NOT_FOUND;
1760 		else if (errno == EINVAL)
1761 			return LIBUSB_ERROR_INVALID_PARAM;
1762 		else if (errno == ENODEV)
1763 			return LIBUSB_ERROR_NO_DEVICE;
1764 
1765 		usbi_err(HANDLE_CTX(handle), "detach failed, errno=%d", errno);
1766 		return LIBUSB_ERROR_OTHER;
1767 	}
1768 
1769 	return 0;
1770 }
1771 
op_attach_kernel_driver(struct libusb_device_handle * handle,uint8_t interface)1772 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1773 	uint8_t interface)
1774 {
1775 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1776 	int fd = hpriv->fd;
1777 	struct usbfs_ioctl command;
1778 	int r;
1779 
1780 	command.ifno = interface;
1781 	command.ioctl_code = IOCTL_USBFS_CONNECT;
1782 	command.data = NULL;
1783 
1784 	r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1785 	if (r < 0) {
1786 		if (errno == ENODATA)
1787 			return LIBUSB_ERROR_NOT_FOUND;
1788 		else if (errno == EINVAL)
1789 			return LIBUSB_ERROR_INVALID_PARAM;
1790 		else if (errno == ENODEV)
1791 			return LIBUSB_ERROR_NO_DEVICE;
1792 		else if (errno == EBUSY)
1793 			return LIBUSB_ERROR_BUSY;
1794 
1795 		usbi_err(HANDLE_CTX(handle), "attach failed, errno=%d", errno);
1796 		return LIBUSB_ERROR_OTHER;
1797 	} else if (r == 0) {
1798 		return LIBUSB_ERROR_NOT_FOUND;
1799 	}
1800 
1801 	return 0;
1802 }
1803 
detach_kernel_driver_and_claim(struct libusb_device_handle * handle,uint8_t interface)1804 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1805 	uint8_t interface)
1806 {
1807 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1808 	struct usbfs_disconnect_claim dc;
1809 	int r, fd = hpriv->fd;
1810 
1811 	dc.interface = interface;
1812 	strcpy(dc.driver, "usbfs");
1813 	dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1814 	r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1815 	if (r == 0)
1816 		return 0;
1817 	switch (errno) {
1818 	case ENOTTY:
1819 		break;
1820 	case EBUSY:
1821 		return LIBUSB_ERROR_BUSY;
1822 	case EINVAL:
1823 		return LIBUSB_ERROR_INVALID_PARAM;
1824 	case ENODEV:
1825 		return LIBUSB_ERROR_NO_DEVICE;
1826 	default:
1827 		usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1828 		return LIBUSB_ERROR_OTHER;
1829 	}
1830 
1831 	/* Fallback code for kernels which don't support the
1832 	   disconnect-and-claim ioctl */
1833 	r = op_detach_kernel_driver(handle, interface);
1834 	if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1835 		return r;
1836 
1837 	return claim_interface(handle, interface);
1838 }
1839 
op_claim_interface(struct libusb_device_handle * handle,uint8_t interface)1840 static int op_claim_interface(struct libusb_device_handle *handle, uint8_t interface)
1841 {
1842 	if (handle->auto_detach_kernel_driver)
1843 		return detach_kernel_driver_and_claim(handle, interface);
1844 	else
1845 		return claim_interface(handle, interface);
1846 }
1847 
op_release_interface(struct libusb_device_handle * handle,uint8_t interface)1848 static int op_release_interface(struct libusb_device_handle *handle, uint8_t interface)
1849 {
1850 	int r;
1851 
1852 	r = release_interface(handle, interface);
1853 	if (r)
1854 		return r;
1855 
1856 	if (handle->auto_detach_kernel_driver)
1857 		op_attach_kernel_driver(handle, interface);
1858 
1859 	return 0;
1860 }
1861 
op_destroy_device(struct libusb_device * dev)1862 static void op_destroy_device(struct libusb_device *dev)
1863 {
1864 	struct linux_device_priv *priv = usbi_get_device_priv(dev);
1865 
1866 	free(priv->config_descriptors);
1867 	free(priv->descriptors);
1868 	free(priv->sysfs_dir);
1869 }
1870 
1871 /* URBs are discarded in reverse order of submission to avoid races. */
discard_urbs(struct usbi_transfer * itransfer,int first,int last_plus_one)1872 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1873 {
1874 	struct libusb_transfer *transfer =
1875 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1876 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1877 	struct linux_device_handle_priv *hpriv =
1878 		usbi_get_device_handle_priv(transfer->dev_handle);
1879 	int i, ret = 0;
1880 	struct usbfs_urb *urb;
1881 
1882 	for (i = last_plus_one - 1; i >= first; i--) {
1883 		if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1884 			urb = tpriv->iso_urbs[i];
1885 		else
1886 			urb = &tpriv->urbs[i];
1887 
1888 		if (ioctl(hpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1889 			continue;
1890 
1891 		if (errno == EINVAL) {
1892 			usbi_dbg(TRANSFER_CTX(transfer), "URB not found --> assuming ready to be reaped");
1893 			if (i == (last_plus_one - 1))
1894 				ret = LIBUSB_ERROR_NOT_FOUND;
1895 		} else if (errno == ENODEV) {
1896 			usbi_dbg(TRANSFER_CTX(transfer), "Device not found for URB --> assuming ready to be reaped");
1897 			ret = LIBUSB_ERROR_NO_DEVICE;
1898 		} else {
1899 			usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1900 			ret = LIBUSB_ERROR_OTHER;
1901 		}
1902 	}
1903 	return ret;
1904 }
1905 
free_iso_urbs(struct linux_transfer_priv * tpriv)1906 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1907 {
1908 	int i;
1909 
1910 	for (i = 0; i < tpriv->num_urbs; i++) {
1911 		struct usbfs_urb *urb = tpriv->iso_urbs[i];
1912 
1913 		if (!urb)
1914 			break;
1915 		free(urb);
1916 	}
1917 
1918 	free(tpriv->iso_urbs);
1919 	tpriv->iso_urbs = NULL;
1920 }
1921 
submit_bulk_transfer(struct usbi_transfer * itransfer)1922 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1923 {
1924 	struct libusb_transfer *transfer =
1925 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1926 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1927 	struct linux_device_handle_priv *hpriv =
1928 		usbi_get_device_handle_priv(transfer->dev_handle);
1929 	struct usbfs_urb *urbs;
1930 	int is_out = IS_XFEROUT(transfer);
1931 	int bulk_buffer_len, use_bulk_continuation;
1932 	int num_urbs;
1933 	int last_urb_partial = 0;
1934 	int r;
1935 	int i;
1936 
1937 	/*
1938 	 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1939 	 * around this by splitting large transfers into 16k blocks, and then
1940 	 * submit all urbs at once. it would be simpler to submit one urb at
1941 	 * a time, but there is a big performance gain doing it this way.
1942 	 *
1943 	 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1944 	 * using arbitrary large transfers can still be a bad idea though, as
1945 	 * the kernel needs to allocate physical contiguous memory for this,
1946 	 * which may fail for large buffers.
1947 	 *
1948 	 * The kernel solves this problem by splitting the transfer into
1949 	 * blocks itself when the host-controller is scatter-gather capable
1950 	 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1951 	 *
1952 	 * Last, there is the issue of short-transfers when splitting, for
1953 	 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1954 	 * is needed, but this is not always available.
1955 	 */
1956 	if (hpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1957 		/* Good! Just submit everything in one go */
1958 		bulk_buffer_len = transfer->length ? transfer->length : 1;
1959 		use_bulk_continuation = 0;
1960 	} else if (hpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1961 		/* Split the transfers and use bulk-continuation to
1962 		   avoid issues with short-transfers */
1963 		bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1964 		use_bulk_continuation = 1;
1965 	} else if (hpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1966 		/* Don't split, assume the kernel can alloc the buffer
1967 		   (otherwise the submit will fail with -ENOMEM) */
1968 		bulk_buffer_len = transfer->length ? transfer->length : 1;
1969 		use_bulk_continuation = 0;
1970 	} else {
1971 		/* Bad, splitting without bulk-continuation, short transfers
1972 		   which end before the last urb will not work reliable! */
1973 		/* Note we don't warn here as this is "normal" on kernels <
1974 		   2.6.32 and not a problem for most applications */
1975 		bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1976 		use_bulk_continuation = 0;
1977 	}
1978 
1979 	num_urbs = transfer->length / bulk_buffer_len;
1980 
1981 	if (transfer->length == 0) {
1982 		num_urbs = 1;
1983 	} else if ((transfer->length % bulk_buffer_len) > 0) {
1984 		last_urb_partial = 1;
1985 		num_urbs++;
1986 	}
1987 	usbi_dbg(TRANSFER_CTX(transfer), "need %d urbs for new transfer with length %d", num_urbs, transfer->length);
1988 	urbs = calloc(num_urbs, sizeof(*urbs));
1989 	if (!urbs)
1990 		return LIBUSB_ERROR_NO_MEM;
1991 	tpriv->urbs = urbs;
1992 	tpriv->num_urbs = num_urbs;
1993 	tpriv->num_retired = 0;
1994 	tpriv->reap_action = NORMAL;
1995 	tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1996 
1997 	for (i = 0; i < num_urbs; i++) {
1998 		struct usbfs_urb *urb = &urbs[i];
1999 
2000 		urb->usercontext = itransfer;
2001 		switch (transfer->type) {
2002 		case LIBUSB_TRANSFER_TYPE_BULK:
2003 			urb->type = USBFS_URB_TYPE_BULK;
2004 			urb->stream_id = 0;
2005 			break;
2006 		case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2007 			urb->type = USBFS_URB_TYPE_BULK;
2008 			urb->stream_id = itransfer->stream_id;
2009 			break;
2010 		case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2011 			urb->type = USBFS_URB_TYPE_INTERRUPT;
2012 			break;
2013 		}
2014 		urb->endpoint = transfer->endpoint;
2015 		urb->buffer = transfer->buffer + (i * bulk_buffer_len);
2016 
2017 		/* don't set the short not ok flag for the last URB */
2018 		if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
2019 			urb->flags = USBFS_URB_SHORT_NOT_OK;
2020 
2021 		if (i == num_urbs - 1 && last_urb_partial)
2022 			urb->buffer_length = transfer->length % bulk_buffer_len;
2023 		else if (transfer->length == 0)
2024 			urb->buffer_length = 0;
2025 		else
2026 			urb->buffer_length = bulk_buffer_len;
2027 
2028 		if (i > 0 && use_bulk_continuation)
2029 			urb->flags |= USBFS_URB_BULK_CONTINUATION;
2030 
2031 		/* we have already checked that the flag is supported */
2032 		if (is_out && i == num_urbs - 1 &&
2033 		    (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
2034 			urb->flags |= USBFS_URB_ZERO_PACKET;
2035 
2036 		r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2037 		if (r == 0)
2038 			continue;
2039 
2040 		if (errno == ENODEV) {
2041 			r = LIBUSB_ERROR_NO_DEVICE;
2042 		} else if (errno == ENOMEM) {
2043 			r = LIBUSB_ERROR_NO_MEM;
2044 		} else {
2045 			usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2046 			r = LIBUSB_ERROR_IO;
2047 		}
2048 
2049 		/* if the first URB submission fails, we can simply free up and
2050 		 * return failure immediately. */
2051 		if (i == 0) {
2052 			usbi_dbg(TRANSFER_CTX(transfer), "first URB failed, easy peasy");
2053 			free(urbs);
2054 			tpriv->urbs = NULL;
2055 			return r;
2056 		}
2057 
2058 		/* if it's not the first URB that failed, the situation is a bit
2059 		 * tricky. we may need to discard all previous URBs. there are
2060 		 * complications:
2061 		 *  - discarding is asynchronous - discarded urbs will be reaped
2062 		 *    later. the user must not have freed the transfer when the
2063 		 *    discarded URBs are reaped, otherwise libusb will be using
2064 		 *    freed memory.
2065 		 *  - the earlier URBs may have completed successfully and we do
2066 		 *    not want to throw away any data.
2067 		 *  - this URB failing may be no error; EREMOTEIO means that
2068 		 *    this transfer simply didn't need all the URBs we submitted
2069 		 * so, we report that the transfer was submitted successfully and
2070 		 * in case of error we discard all previous URBs. later when
2071 		 * the final reap completes we can report error to the user,
2072 		 * or success if an earlier URB was completed successfully.
2073 		 */
2074 		tpriv->reap_action = errno == EREMOTEIO ? COMPLETED_EARLY : SUBMIT_FAILED;
2075 
2076 		/* The URBs we haven't submitted yet we count as already
2077 		 * retired. */
2078 		tpriv->num_retired += num_urbs - i;
2079 
2080 		/* If we completed short then don't try to discard. */
2081 		if (tpriv->reap_action == COMPLETED_EARLY)
2082 			return 0;
2083 
2084 		discard_urbs(itransfer, 0, i);
2085 
2086 		usbi_dbg(TRANSFER_CTX(transfer), "reporting successful submission but waiting for %d "
2087 			 "discards before reporting error", i);
2088 		return 0;
2089 	}
2090 
2091 	return 0;
2092 }
2093 
submit_iso_transfer(struct usbi_transfer * itransfer)2094 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2095 {
2096 	struct libusb_transfer *transfer =
2097 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2098 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2099 	struct linux_device_handle_priv *hpriv =
2100 		usbi_get_device_handle_priv(transfer->dev_handle);
2101 	struct usbfs_urb **urbs;
2102 	int num_packets = transfer->num_iso_packets;
2103 	int num_packets_remaining;
2104 	int i, j;
2105 	int num_urbs;
2106 	unsigned int packet_len;
2107 	unsigned int total_len = 0;
2108 	unsigned char *urb_buffer = transfer->buffer;
2109 
2110 	if (num_packets < 1)
2111 		return LIBUSB_ERROR_INVALID_PARAM;
2112 
2113 	/* usbfs places arbitrary limits on iso URBs. this limit has changed
2114 	 * at least three times, but we attempt to detect this limit during
2115 	 * init and check it here. if the kernel rejects the request due to
2116 	 * its size, we return an error indicating such to the user.
2117 	 */
2118 	for (i = 0; i < num_packets; i++) {
2119 		packet_len = transfer->iso_packet_desc[i].length;
2120 
2121 		if (packet_len > max_iso_packet_len) {
2122 			usbi_warn(TRANSFER_CTX(transfer),
2123 				  "iso packet length of %u bytes exceeds maximum of %u bytes",
2124 				  packet_len, max_iso_packet_len);
2125 			return LIBUSB_ERROR_INVALID_PARAM;
2126 		}
2127 
2128 		total_len += packet_len;
2129 	}
2130 
2131 	if (transfer->length < (int)total_len)
2132 		return LIBUSB_ERROR_INVALID_PARAM;
2133 
2134 	/* usbfs limits the number of iso packets per URB */
2135 	num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2136 
2137 	usbi_dbg(TRANSFER_CTX(transfer), "need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2138 
2139 	urbs = calloc(num_urbs, sizeof(*urbs));
2140 	if (!urbs)
2141 		return LIBUSB_ERROR_NO_MEM;
2142 
2143 	tpriv->iso_urbs = urbs;
2144 	tpriv->num_urbs = num_urbs;
2145 	tpriv->num_retired = 0;
2146 	tpriv->reap_action = NORMAL;
2147 	tpriv->iso_packet_offset = 0;
2148 
2149 	/* allocate + initialize each URB with the correct number of packets */
2150 	num_packets_remaining = num_packets;
2151 	for (i = 0, j = 0; i < num_urbs; i++) {
2152 		int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2153 		struct usbfs_urb *urb;
2154 		size_t alloc_size;
2155 		int k;
2156 
2157 		alloc_size = sizeof(*urb)
2158 			+ (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2159 		urb = calloc(1, alloc_size);
2160 		if (!urb) {
2161 			free_iso_urbs(tpriv);
2162 			return LIBUSB_ERROR_NO_MEM;
2163 		}
2164 		urbs[i] = urb;
2165 
2166 		/* populate packet lengths */
2167 		for (k = 0; k < num_packets_in_urb; j++, k++) {
2168 			packet_len = transfer->iso_packet_desc[j].length;
2169 			urb->buffer_length += packet_len;
2170 			urb->iso_frame_desc[k].length = packet_len;
2171 		}
2172 
2173 		urb->usercontext = itransfer;
2174 		urb->type = USBFS_URB_TYPE_ISO;
2175 		/* FIXME: interface for non-ASAP data? */
2176 		urb->flags = USBFS_URB_ISO_ASAP;
2177 		urb->endpoint = transfer->endpoint;
2178 		urb->number_of_packets = num_packets_in_urb;
2179 		urb->buffer = urb_buffer;
2180 
2181 		urb_buffer += urb->buffer_length;
2182 		num_packets_remaining -= num_packets_in_urb;
2183 	}
2184 
2185 	/* submit URBs */
2186 	for (i = 0; i < num_urbs; i++) {
2187 		int r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2188 
2189 		if (r == 0)
2190 			continue;
2191 
2192 		if (errno == ENODEV) {
2193 			r = LIBUSB_ERROR_NO_DEVICE;
2194 		} else if (errno == EINVAL) {
2195 			usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2196 			r = LIBUSB_ERROR_INVALID_PARAM;
2197 		} else if (errno == EMSGSIZE) {
2198 			usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2199 			r = LIBUSB_ERROR_INVALID_PARAM;
2200 		} else {
2201 			usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2202 			r = LIBUSB_ERROR_IO;
2203 		}
2204 
2205 		/* if the first URB submission fails, we can simply free up and
2206 		 * return failure immediately. */
2207 		if (i == 0) {
2208 			usbi_dbg(TRANSFER_CTX(transfer), "first URB failed, easy peasy");
2209 			free_iso_urbs(tpriv);
2210 			return r;
2211 		}
2212 
2213 		/* if it's not the first URB that failed, the situation is a bit
2214 		 * tricky. we must discard all previous URBs. there are
2215 		 * complications:
2216 		 *  - discarding is asynchronous - discarded urbs will be reaped
2217 		 *    later. the user must not have freed the transfer when the
2218 		 *    discarded URBs are reaped, otherwise libusb will be using
2219 		 *    freed memory.
2220 		 *  - the earlier URBs may have completed successfully and we do
2221 		 *    not want to throw away any data.
2222 		 * so, in this case we discard all the previous URBs BUT we report
2223 		 * that the transfer was submitted successfully. then later when
2224 		 * the final discard completes we can report error to the user.
2225 		 */
2226 		tpriv->reap_action = SUBMIT_FAILED;
2227 
2228 		/* The URBs we haven't submitted yet we count as already
2229 		 * retired. */
2230 		tpriv->num_retired = num_urbs - i;
2231 		discard_urbs(itransfer, 0, i);
2232 
2233 		usbi_dbg(TRANSFER_CTX(transfer), "reporting successful submission but waiting for %d "
2234 			 "discards before reporting error", i);
2235 		return 0;
2236 	}
2237 
2238 	return 0;
2239 }
2240 
submit_control_transfer(struct usbi_transfer * itransfer)2241 static int submit_control_transfer(struct usbi_transfer *itransfer)
2242 {
2243 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2244 	struct libusb_transfer *transfer =
2245 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2246 	struct linux_device_handle_priv *hpriv =
2247 		usbi_get_device_handle_priv(transfer->dev_handle);
2248 	struct usbfs_urb *urb;
2249 	int r;
2250 
2251 	if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2252 		return LIBUSB_ERROR_INVALID_PARAM;
2253 
2254 	urb = calloc(1, sizeof(*urb));
2255 	if (!urb)
2256 		return LIBUSB_ERROR_NO_MEM;
2257 	tpriv->urbs = urb;
2258 	tpriv->num_urbs = 1;
2259 	tpriv->reap_action = NORMAL;
2260 
2261 	urb->usercontext = itransfer;
2262 	urb->type = USBFS_URB_TYPE_CONTROL;
2263 	urb->endpoint = transfer->endpoint;
2264 	urb->buffer = transfer->buffer;
2265 	urb->buffer_length = transfer->length;
2266 
2267 	r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2268 	if (r < 0) {
2269 		free(urb);
2270 		tpriv->urbs = NULL;
2271 		if (errno == ENODEV)
2272 			return LIBUSB_ERROR_NO_DEVICE;
2273 
2274 		usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2275 		return LIBUSB_ERROR_IO;
2276 	}
2277 	return 0;
2278 }
2279 
op_submit_transfer(struct usbi_transfer * itransfer)2280 static int op_submit_transfer(struct usbi_transfer *itransfer)
2281 {
2282 	struct libusb_transfer *transfer =
2283 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2284 
2285 	switch (transfer->type) {
2286 	case LIBUSB_TRANSFER_TYPE_CONTROL:
2287 		return submit_control_transfer(itransfer);
2288 	case LIBUSB_TRANSFER_TYPE_BULK:
2289 	case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2290 		return submit_bulk_transfer(itransfer);
2291 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2292 		return submit_bulk_transfer(itransfer);
2293 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2294 		return submit_iso_transfer(itransfer);
2295 	default:
2296 		usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2297 		return LIBUSB_ERROR_INVALID_PARAM;
2298 	}
2299 }
2300 
op_cancel_transfer(struct usbi_transfer * itransfer)2301 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2302 {
2303 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2304 	struct libusb_transfer *transfer =
2305 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2306 	int r;
2307 
2308 	if (!tpriv->urbs)
2309 		return LIBUSB_ERROR_NOT_FOUND;
2310 
2311 	r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2312 	if (r != 0)
2313 		return r;
2314 
2315 	switch (transfer->type) {
2316 	case LIBUSB_TRANSFER_TYPE_BULK:
2317 	case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2318 		if (tpriv->reap_action == ERROR)
2319 			break;
2320 		/* else, fall through */
2321 	default:
2322 		tpriv->reap_action = CANCELLED;
2323 	}
2324 
2325 	return 0;
2326 }
2327 
op_clear_transfer_priv(struct usbi_transfer * itransfer)2328 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2329 {
2330 	struct libusb_transfer *transfer =
2331 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2332 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2333 
2334 	switch (transfer->type) {
2335 	case LIBUSB_TRANSFER_TYPE_CONTROL:
2336 	case LIBUSB_TRANSFER_TYPE_BULK:
2337 	case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2338 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2339 		if (tpriv->urbs) {
2340 			free(tpriv->urbs);
2341 			tpriv->urbs = NULL;
2342 		}
2343 		break;
2344 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2345 		if (tpriv->iso_urbs) {
2346 			free_iso_urbs(tpriv);
2347 			tpriv->iso_urbs = NULL;
2348 		}
2349 		break;
2350 	default:
2351 		usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2352 	}
2353 }
2354 
handle_bulk_completion(struct usbi_transfer * itransfer,struct usbfs_urb * urb)2355 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2356 	struct usbfs_urb *urb)
2357 {
2358 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2359 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2360 	int urb_idx = urb - tpriv->urbs;
2361 
2362 	usbi_mutex_lock(&itransfer->lock);
2363 	usbi_dbg(TRANSFER_CTX(transfer), "handling completion status %d of bulk urb %d/%d", urb->status,
2364 		 urb_idx + 1, tpriv->num_urbs);
2365 
2366 	tpriv->num_retired++;
2367 
2368 	if (tpriv->reap_action != NORMAL) {
2369 		/* cancelled, submit_fail, or completed early */
2370 		usbi_dbg(TRANSFER_CTX(transfer), "abnormal reap: urb status %d", urb->status);
2371 
2372 		/* even though we're in the process of cancelling, it's possible that
2373 		 * we may receive some data in these URBs that we don't want to lose.
2374 		 * examples:
2375 		 * 1. while the kernel is cancelling all the packets that make up an
2376 		 *    URB, a few of them might complete. so we get back a successful
2377 		 *    cancellation *and* some data.
2378 		 * 2. we receive a short URB which marks the early completion condition,
2379 		 *    so we start cancelling the remaining URBs. however, we're too
2380 		 *    slow and another URB completes (or at least completes partially).
2381 		 *    (this can't happen since we always use BULK_CONTINUATION.)
2382 		 *
2383 		 * When this happens, our objectives are not to lose any "surplus" data,
2384 		 * and also to stick it at the end of the previously-received data
2385 		 * (closing any holes), so that libusb reports the total amount of
2386 		 * transferred data and presents it in a contiguous chunk.
2387 		 */
2388 		if (urb->actual_length > 0) {
2389 			unsigned char *target = transfer->buffer + itransfer->transferred;
2390 
2391 			usbi_dbg(TRANSFER_CTX(transfer), "received %d bytes of surplus data", urb->actual_length);
2392 			if (urb->buffer != target) {
2393 				usbi_dbg(TRANSFER_CTX(transfer), "moving surplus data from offset %zu to offset %zu",
2394 					 (unsigned char *)urb->buffer - transfer->buffer,
2395 					 target - transfer->buffer);
2396 				memmove(target, urb->buffer, urb->actual_length);
2397 			}
2398 			itransfer->transferred += urb->actual_length;
2399 		}
2400 
2401 		if (tpriv->num_retired == tpriv->num_urbs) {
2402 			usbi_dbg(TRANSFER_CTX(transfer), "abnormal reap: last URB handled, reporting");
2403 			if (tpriv->reap_action != COMPLETED_EARLY &&
2404 			    tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2405 				tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2406 			goto completed;
2407 		}
2408 		goto out_unlock;
2409 	}
2410 
2411 	itransfer->transferred += urb->actual_length;
2412 
2413 	/* Many of these errors can occur on *any* urb of a multi-urb
2414 	 * transfer.  When they do, we tear down the rest of the transfer.
2415 	 */
2416 	switch (urb->status) {
2417 	case 0:
2418 		break;
2419 	case -EREMOTEIO: /* short transfer */
2420 		break;
2421 	case -ENOENT: /* cancelled */
2422 	case -ECONNRESET:
2423 		break;
2424 	case -ENODEV:
2425 	case -ESHUTDOWN:
2426 		usbi_dbg(TRANSFER_CTX(transfer), "device removed");
2427 		tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2428 		goto cancel_remaining;
2429 	case -EPIPE:
2430 		usbi_dbg(TRANSFER_CTX(transfer), "detected endpoint stall");
2431 		if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2432 			tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2433 		goto cancel_remaining;
2434 	case -EOVERFLOW:
2435 		/* overflow can only ever occur in the last urb */
2436 		usbi_dbg(TRANSFER_CTX(transfer), "overflow, actual_length=%d", urb->actual_length);
2437 		if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2438 			tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2439 		goto completed;
2440 	case -ETIME:
2441 	case -EPROTO:
2442 	case -EILSEQ:
2443 	case -ECOMM:
2444 	case -ENOSR:
2445 		usbi_dbg(TRANSFER_CTX(transfer), "low-level bus error %d", urb->status);
2446 		tpriv->reap_action = ERROR;
2447 		goto cancel_remaining;
2448 	default:
2449 		usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2450 		tpriv->reap_action = ERROR;
2451 		goto cancel_remaining;
2452 	}
2453 
2454 	/* if we've reaped all urbs or we got less data than requested then we're
2455 	 * done */
2456 	if (tpriv->num_retired == tpriv->num_urbs) {
2457 		usbi_dbg(TRANSFER_CTX(transfer), "all URBs in transfer reaped --> complete!");
2458 		goto completed;
2459 	} else if (urb->actual_length < urb->buffer_length) {
2460 		usbi_dbg(TRANSFER_CTX(transfer), "short transfer %d/%d --> complete!",
2461 			 urb->actual_length, urb->buffer_length);
2462 		if (tpriv->reap_action == NORMAL)
2463 			tpriv->reap_action = COMPLETED_EARLY;
2464 	} else {
2465 		goto out_unlock;
2466 	}
2467 
2468 cancel_remaining:
2469 	if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2470 		tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2471 
2472 	if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2473 		goto completed;
2474 
2475 	/* cancel remaining urbs and wait for their completion before
2476 	 * reporting results */
2477 	discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2478 
2479 out_unlock:
2480 	usbi_mutex_unlock(&itransfer->lock);
2481 	return 0;
2482 
2483 completed:
2484 	free(tpriv->urbs);
2485 	tpriv->urbs = NULL;
2486 	usbi_mutex_unlock(&itransfer->lock);
2487 	return tpriv->reap_action == CANCELLED ?
2488 		usbi_handle_transfer_cancellation(itransfer) :
2489 		usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2490 }
2491 
handle_iso_completion(struct usbi_transfer * itransfer,struct usbfs_urb * urb)2492 static int handle_iso_completion(struct usbi_transfer *itransfer,
2493 	struct usbfs_urb *urb)
2494 {
2495 	struct libusb_transfer *transfer =
2496 		USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2497 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2498 	int num_urbs = tpriv->num_urbs;
2499 	int urb_idx = 0;
2500 	int i;
2501 	enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2502 
2503 	usbi_mutex_lock(&itransfer->lock);
2504 	for (i = 0; i < num_urbs; i++) {
2505 		if (urb == tpriv->iso_urbs[i]) {
2506 			urb_idx = i + 1;
2507 			break;
2508 		}
2509 	}
2510 	if (urb_idx == 0) {
2511 		usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2512 		usbi_mutex_unlock(&itransfer->lock);
2513 		return LIBUSB_ERROR_NOT_FOUND;
2514 	}
2515 
2516 	usbi_dbg(TRANSFER_CTX(transfer), "handling completion status %d of iso urb %d/%d", urb->status,
2517 		 urb_idx, num_urbs);
2518 
2519 	/* copy isochronous results back in */
2520 
2521 	for (i = 0; i < urb->number_of_packets; i++) {
2522 		struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2523 		struct libusb_iso_packet_descriptor *lib_desc =
2524 			&transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2525 
2526 		lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2527 		switch (urb_desc->status) {
2528 		case 0:
2529 			break;
2530 		case -ENOENT: /* cancelled */
2531 		case -ECONNRESET:
2532 			break;
2533 		case -ENODEV:
2534 		case -ESHUTDOWN:
2535 			usbi_dbg(TRANSFER_CTX(transfer), "packet %d - device removed", i);
2536 			lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2537 			break;
2538 		case -EPIPE:
2539 			usbi_dbg(TRANSFER_CTX(transfer), "packet %d - detected endpoint stall", i);
2540 			lib_desc->status = LIBUSB_TRANSFER_STALL;
2541 			break;
2542 		case -EOVERFLOW:
2543 			usbi_dbg(TRANSFER_CTX(transfer), "packet %d - overflow error", i);
2544 			lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2545 			break;
2546 		case -ETIME:
2547 		case -EPROTO:
2548 		case -EILSEQ:
2549 		case -ECOMM:
2550 		case -ENOSR:
2551 		case -EXDEV:
2552 			usbi_dbg(TRANSFER_CTX(transfer), "packet %d - low-level USB error %d", i, urb_desc->status);
2553 			lib_desc->status = LIBUSB_TRANSFER_ERROR;
2554 			break;
2555 		default:
2556 			usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2557 				  i, urb_desc->status);
2558 			lib_desc->status = LIBUSB_TRANSFER_ERROR;
2559 			break;
2560 		}
2561 		lib_desc->actual_length = urb_desc->actual_length;
2562 	}
2563 
2564 	tpriv->num_retired++;
2565 
2566 	if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2567 		usbi_dbg(TRANSFER_CTX(transfer), "CANCEL: urb status %d", urb->status);
2568 
2569 		if (tpriv->num_retired == num_urbs) {
2570 			usbi_dbg(TRANSFER_CTX(transfer), "CANCEL: last URB handled, reporting");
2571 			free_iso_urbs(tpriv);
2572 			if (tpriv->reap_action == CANCELLED) {
2573 				usbi_mutex_unlock(&itransfer->lock);
2574 				return usbi_handle_transfer_cancellation(itransfer);
2575 			} else {
2576 				usbi_mutex_unlock(&itransfer->lock);
2577 				return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2578 			}
2579 		}
2580 		goto out;
2581 	}
2582 
2583 	switch (urb->status) {
2584 	case 0:
2585 		break;
2586 	case -ENOENT: /* cancelled */
2587 	case -ECONNRESET:
2588 		break;
2589 	case -ESHUTDOWN:
2590 		usbi_dbg(TRANSFER_CTX(transfer), "device removed");
2591 		status = LIBUSB_TRANSFER_NO_DEVICE;
2592 		break;
2593 	default:
2594 		usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2595 		status = LIBUSB_TRANSFER_ERROR;
2596 		break;
2597 	}
2598 
2599 	/* if we've reaped all urbs then we're done */
2600 	if (tpriv->num_retired == num_urbs) {
2601 		usbi_dbg(TRANSFER_CTX(transfer), "all URBs in transfer reaped --> complete!");
2602 		free_iso_urbs(tpriv);
2603 		usbi_mutex_unlock(&itransfer->lock);
2604 		return usbi_handle_transfer_completion(itransfer, status);
2605 	}
2606 
2607 out:
2608 	usbi_mutex_unlock(&itransfer->lock);
2609 	return 0;
2610 }
2611 
handle_control_completion(struct usbi_transfer * itransfer,struct usbfs_urb * urb)2612 static int handle_control_completion(struct usbi_transfer *itransfer,
2613 	struct usbfs_urb *urb)
2614 {
2615 	struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2616 	int status;
2617 
2618 	usbi_mutex_lock(&itransfer->lock);
2619 	usbi_dbg(ITRANSFER_CTX(itransfer), "handling completion status %d", urb->status);
2620 
2621 	itransfer->transferred += urb->actual_length;
2622 
2623 	if (tpriv->reap_action == CANCELLED) {
2624 		if (urb->status && urb->status != -ENOENT)
2625 			usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2626 				  urb->status);
2627 		free(tpriv->urbs);
2628 		tpriv->urbs = NULL;
2629 		usbi_mutex_unlock(&itransfer->lock);
2630 		return usbi_handle_transfer_cancellation(itransfer);
2631 	}
2632 
2633 	switch (urb->status) {
2634 	case 0:
2635 		status = LIBUSB_TRANSFER_COMPLETED;
2636 		break;
2637 	case -ENOENT: /* cancelled */
2638 		status = LIBUSB_TRANSFER_CANCELLED;
2639 		break;
2640 	case -ENODEV:
2641 	case -ESHUTDOWN:
2642 		usbi_dbg(ITRANSFER_CTX(itransfer), "device removed");
2643 		status = LIBUSB_TRANSFER_NO_DEVICE;
2644 		break;
2645 	case -EPIPE:
2646 		usbi_dbg(ITRANSFER_CTX(itransfer), "unsupported control request");
2647 		status = LIBUSB_TRANSFER_STALL;
2648 		break;
2649 	case -EOVERFLOW:
2650 		usbi_dbg(ITRANSFER_CTX(itransfer), "overflow, actual_length=%d", urb->actual_length);
2651 		status = LIBUSB_TRANSFER_OVERFLOW;
2652 		break;
2653 	case -ETIME:
2654 	case -EPROTO:
2655 	case -EILSEQ:
2656 	case -ECOMM:
2657 	case -ENOSR:
2658 		usbi_dbg(ITRANSFER_CTX(itransfer), "low-level bus error %d", urb->status);
2659 		status = LIBUSB_TRANSFER_ERROR;
2660 		break;
2661 	default:
2662 		usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2663 		status = LIBUSB_TRANSFER_ERROR;
2664 		break;
2665 	}
2666 
2667 	free(tpriv->urbs);
2668 	tpriv->urbs = NULL;
2669 	usbi_mutex_unlock(&itransfer->lock);
2670 	return usbi_handle_transfer_completion(itransfer, status);
2671 }
2672 
reap_for_handle(struct libusb_device_handle * handle)2673 static int reap_for_handle(struct libusb_device_handle *handle)
2674 {
2675 	struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
2676 	int r;
2677 	struct usbfs_urb *urb = NULL;
2678 	struct usbi_transfer *itransfer;
2679 	struct libusb_transfer *transfer;
2680 
2681 	r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2682 	if (r < 0) {
2683 		if (errno == EAGAIN)
2684 			return 1;
2685 		if (errno == ENODEV)
2686 			return LIBUSB_ERROR_NO_DEVICE;
2687 
2688 		usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2689 		return LIBUSB_ERROR_IO;
2690 	}
2691 
2692 	itransfer = urb->usercontext;
2693 	transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2694 
2695 	usbi_dbg(HANDLE_CTX(handle), "urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2696 
2697 	switch (transfer->type) {
2698 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2699 		return handle_iso_completion(itransfer, urb);
2700 	case LIBUSB_TRANSFER_TYPE_BULK:
2701 	case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2702 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2703 		return handle_bulk_completion(itransfer, urb);
2704 	case LIBUSB_TRANSFER_TYPE_CONTROL:
2705 		return handle_control_completion(itransfer, urb);
2706 	default:
2707 		usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2708 		return LIBUSB_ERROR_OTHER;
2709 	}
2710 }
2711 
op_handle_events(struct libusb_context * ctx,void * event_data,unsigned int count,unsigned int num_ready)2712 static int op_handle_events(struct libusb_context *ctx,
2713 	void *event_data, unsigned int count, unsigned int num_ready)
2714 {
2715 	struct pollfd *fds = event_data;
2716 	unsigned int n;
2717 	int r;
2718 
2719 	usbi_mutex_lock(&ctx->open_devs_lock);
2720 	for (n = 0; n < count && num_ready > 0; n++) {
2721 		struct pollfd *pollfd = &fds[n];
2722 		struct libusb_device_handle *handle;
2723 		struct linux_device_handle_priv *hpriv = NULL;
2724 		int reap_count;
2725 
2726 		if (!pollfd->revents)
2727 			continue;
2728 
2729 		num_ready--;
2730 		for_each_open_device(ctx, handle) {
2731 			hpriv = usbi_get_device_handle_priv(handle);
2732 			if (hpriv->fd == pollfd->fd)
2733 				break;
2734 		}
2735 
2736 		if (!hpriv || hpriv->fd != pollfd->fd) {
2737 			usbi_err(ctx, "cannot find handle for fd %d",
2738 				 pollfd->fd);
2739 			continue;
2740 		}
2741 
2742 		if (pollfd->revents & POLLERR) {
2743 			/* remove the fd from the pollfd set so that it doesn't continuously
2744 			 * trigger an event, and flag that it has been removed so op_close()
2745 			 * doesn't try to remove it a second time */
2746 			usbi_remove_event_source(HANDLE_CTX(handle), hpriv->fd);
2747 			hpriv->fd_removed = 1;
2748 
2749 			/* device will still be marked as attached if hotplug monitor thread
2750 			 * hasn't processed remove event yet */
2751 			usbi_mutex_static_lock(&linux_hotplug_lock);
2752 			if (usbi_atomic_load(&handle->dev->attached))
2753 				linux_device_disconnected(handle->dev->bus_number,
2754 							  handle->dev->device_address);
2755 			usbi_mutex_static_unlock(&linux_hotplug_lock);
2756 
2757 			if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2758 				do {
2759 					r = reap_for_handle(handle);
2760 				} while (r == 0);
2761 			}
2762 
2763 			usbi_handle_disconnect(handle);
2764 			continue;
2765 		}
2766 
2767 		reap_count = 0;
2768 		do {
2769 			r = reap_for_handle(handle);
2770 		} while (r == 0 && ++reap_count <= 25);
2771 
2772 		if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2773 			continue;
2774 		else if (r < 0)
2775 			goto out;
2776 	}
2777 
2778 	r = 0;
2779 out:
2780 	usbi_mutex_unlock(&ctx->open_devs_lock);
2781 	return r;
2782 }
2783 
2784 const struct usbi_os_backend usbi_backend = {
2785 	.name = "Linux usbfs",
2786 	.caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2787 	.init = op_init,
2788 	.exit = op_exit,
2789 	.set_option = op_set_option,
2790 	.hotplug_poll = op_hotplug_poll,
2791 	.get_active_config_descriptor = op_get_active_config_descriptor,
2792 	.get_config_descriptor = op_get_config_descriptor,
2793 	.get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2794 
2795 	.wrap_sys_device = op_wrap_sys_device,
2796 	.open = op_open,
2797 	.close = op_close,
2798 	.get_configuration = op_get_configuration,
2799 	.set_configuration = op_set_configuration,
2800 	.claim_interface = op_claim_interface,
2801 	.release_interface = op_release_interface,
2802 
2803 	.set_interface_altsetting = op_set_interface,
2804 	.clear_halt = op_clear_halt,
2805 	.reset_device = op_reset_device,
2806 
2807 	.alloc_streams = op_alloc_streams,
2808 	.free_streams = op_free_streams,
2809 
2810 	.dev_mem_alloc = op_dev_mem_alloc,
2811 	.dev_mem_free = op_dev_mem_free,
2812 
2813 	.kernel_driver_active = op_kernel_driver_active,
2814 	.detach_kernel_driver = op_detach_kernel_driver,
2815 	.attach_kernel_driver = op_attach_kernel_driver,
2816 
2817 	.destroy_device = op_destroy_device,
2818 
2819 	.submit_transfer = op_submit_transfer,
2820 	.cancel_transfer = op_cancel_transfer,
2821 	.clear_transfer_priv = op_clear_transfer_priv,
2822 
2823 	.handle_events = op_handle_events,
2824 
2825 	.context_priv_size = sizeof(struct linux_context_priv),
2826 	.device_priv_size = sizeof(struct linux_device_priv),
2827 	.device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2828 	.transfer_priv_size = sizeof(struct linux_transfer_priv),
2829 };
2830