xref: /freebsd/lib/libusb/libusb10.c (revision bca5df45652ae4edd14fa032be8f271e044d32b2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009 Sylvestre Gallon. All rights reserved.
5  * Copyright (c) 2009-2023 Hans Petter Selasky
6  * Copyright (c) 2024 Aymeric Wibo
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifdef LIBUSB_GLOBAL_INCLUDE_FILE
31 #include LIBUSB_GLOBAL_INCLUDE_FILE
32 #else
33 #include <assert.h>
34 #include <errno.h>
35 #include <poll.h>
36 #include <pthread.h>
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <time.h>
44 #include <sys/eventfd.h>
45 #include <sys/fcntl.h>
46 #include <sys/ioctl.h>
47 #include <sys/queue.h>
48 #include <sys/endian.h>
49 #endif
50 
51 #define	libusb_device_handle libusb20_device
52 #define	LIBUSB_LOG_BUFFER_SIZE 1024
53 
54 #include "libusb20.h"
55 #include "libusb20_desc.h"
56 #include "libusb20_int.h"
57 #include "libusb.h"
58 #include "libusb10.h"
59 
60 #define	LIBUSB_NUM_SW_ENDPOINTS	(16 * 4)
61 
62 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
63 struct libusb_context *usbi_default_context = NULL;
64 
65 /* Prototypes */
66 
67 static struct libusb20_transfer *libusb10_get_transfer(struct libusb20_device *, uint8_t, uint8_t);
68 static int libusb10_get_buffsize(struct libusb20_device *, libusb_transfer *);
69 static int libusb10_convert_error(uint8_t status);
70 static void libusb10_complete_transfer(struct libusb20_transfer *, struct libusb_super_transfer *, int);
71 static void libusb10_isoc_proxy(struct libusb20_transfer *);
72 static void libusb10_bulk_intr_proxy(struct libusb20_transfer *);
73 static void libusb10_ctrl_proxy(struct libusb20_transfer *);
74 static void libusb10_submit_transfer_sub(struct libusb20_device *, uint8_t);
75 
76 /*  Library initialisation / deinitialisation */
77 
78 static const struct libusb_version libusb_version = {
79 	.major = 1,
80 	.minor = 0,
81 	.micro = 0,
82 	.nano = 2016,
83 	.rc = "",
84 	.describe = "https://www.freebsd.org"
85 };
86 
87 const struct libusb_version *
libusb_get_version(void)88 libusb_get_version(void)
89 {
90 
91 	return (&libusb_version);
92 }
93 
94 void
libusb_set_debug(libusb_context * ctx,int level)95 libusb_set_debug(libusb_context *ctx, int level)
96 {
97 	ctx = GET_CONTEXT(ctx);
98 	/* debug_fixed is set when the environment overrides libusb_set_debug */
99 	if (ctx && ctx->debug_fixed == 0)
100 		ctx->debug = level;
101 }
102 
103 static void
libusb_set_nonblocking(int f)104 libusb_set_nonblocking(int f)
105 {
106 	int flags;
107 
108 	/*
109 	 * We ignore any failures in this function, hence the
110 	 * non-blocking flag is not critical to the operation of
111 	 * libUSB. We use F_GETFL and F_SETFL to be compatible with
112 	 * Linux.
113 	 */
114 
115 	flags = fcntl(f, F_GETFL, NULL);
116 	if (flags == -1)
117 		return;
118 	flags |= O_NONBLOCK;
119 	fcntl(f, F_SETFL, flags);
120 }
121 
122 void
libusb_interrupt_event_handler(libusb_context * ctx)123 libusb_interrupt_event_handler(libusb_context *ctx)
124 {
125 	int err;
126 
127 	if (ctx == NULL)
128 		return;
129 
130 	err = eventfd_write(ctx->event, 1);
131 	if (err < 0) {
132 		/* ignore error, if any */
133 		DPRINTF(ctx, LIBUSB_LOG_LEVEL_ERROR, "Waking up event loop failed!");
134 	}
135 }
136 
137 int
libusb_init(libusb_context ** context)138 libusb_init(libusb_context **context)
139 {
140 	return (libusb_init_context(context, NULL, 0));
141 }
142 
143 int
libusb_init_context(libusb_context ** context,const struct libusb_init_option option[],int num_options)144 libusb_init_context(libusb_context **context,
145     const struct libusb_init_option option[], int num_options)
146 {
147 	struct libusb_context *ctx;
148 	pthread_condattr_t attr;
149 	char *debug, *ep;
150 
151 	if (num_options < 0)
152 		return (LIBUSB_ERROR_INVALID_PARAM);
153 
154 	ctx = malloc(sizeof(*ctx));
155 	if (!ctx)
156 		return (LIBUSB_ERROR_INVALID_PARAM);
157 
158 	memset(ctx, 0, sizeof(*ctx));
159 	ctx->devd_pipe = -1;
160 
161 	debug = getenv("LIBUSB_DEBUG");
162 	if (debug != NULL) {
163 		/*
164 		 * If LIBUSB_DEBUG is set, we'll honor that first and
165 		 * use it to override any future libusb_set_debug()
166 		 * calls or init options.
167 		 */
168 		errno = 0;
169 		ctx->debug = strtol(debug, &ep, 10);
170 		if (errno == 0 && *ep == '\0') {
171 			ctx->debug_fixed = 1;
172 		} else {
173 			/*
174 			 * LIBUSB_DEBUG conversion failed for some reason, but
175 			 * we don't care about the specifics all that much.  We
176 			 * can't use it either way.  Force it to the default,
177 			 * 0, in case we had a partial number.
178 			 */
179 			ctx->debug = 0;
180 		}
181 	} else {
182 		/*
183 		 * If the LIBUSB_OPTION_LOG_LEVEL is set, honor that.
184 		 */
185 		for (int i = 0; i != num_options; i++) {
186 			if (option[i].option != LIBUSB_OPTION_LOG_LEVEL)
187 				continue;
188 
189 			ctx->debug = (int)option[i].value.ival;
190 			if ((int64_t)ctx->debug == option[i].value.ival) {
191 				ctx->debug_fixed = 1;
192 			} else {
193 				free(ctx);
194 				return (LIBUSB_ERROR_INVALID_PARAM);
195 			}
196 		}
197 	}
198 
199 	TAILQ_INIT(&ctx->pollfds);
200 	TAILQ_INIT(&ctx->tr_done);
201 	TAILQ_INIT(&ctx->hotplug_cbh);
202 	TAILQ_INIT(&ctx->hotplug_devs);
203 
204 	if (pthread_mutex_init(&ctx->ctx_lock, NULL) != 0) {
205 		free(ctx);
206 		return (LIBUSB_ERROR_NO_MEM);
207 	}
208 	if (pthread_mutex_init(&ctx->hotplug_lock, NULL) != 0) {
209 		pthread_mutex_destroy(&ctx->ctx_lock);
210 		free(ctx);
211 		return (LIBUSB_ERROR_NO_MEM);
212 	}
213 	if (pthread_condattr_init(&attr) != 0) {
214 		pthread_mutex_destroy(&ctx->ctx_lock);
215 		pthread_mutex_destroy(&ctx->hotplug_lock);
216 		free(ctx);
217 		return (LIBUSB_ERROR_NO_MEM);
218 	}
219 	if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) != 0) {
220 		pthread_mutex_destroy(&ctx->ctx_lock);
221 		pthread_mutex_destroy(&ctx->hotplug_lock);
222 		pthread_condattr_destroy(&attr);
223 		free(ctx);
224 		return (LIBUSB_ERROR_OTHER);
225 	}
226 	if (pthread_cond_init(&ctx->ctx_cond, &attr) != 0) {
227 		pthread_mutex_destroy(&ctx->ctx_lock);
228 		pthread_mutex_destroy(&ctx->hotplug_lock);
229 		pthread_condattr_destroy(&attr);
230 		free(ctx);
231 		return (LIBUSB_ERROR_NO_MEM);
232 	}
233 	pthread_condattr_destroy(&attr);
234 
235 	ctx->ctx_handler = NO_THREAD;
236 	ctx->hotplug_handler = NO_THREAD;
237 
238 	ctx->event = eventfd(0, EFD_NONBLOCK);
239 	if (ctx->event < 0) {
240 		pthread_mutex_destroy(&ctx->ctx_lock);
241 		pthread_mutex_destroy(&ctx->hotplug_lock);
242 		pthread_cond_destroy(&ctx->ctx_cond);
243 		free(ctx);
244 		return (LIBUSB_ERROR_OTHER);
245 	}
246 
247 	libusb10_add_pollfd(ctx, &ctx->ctx_poll, NULL, ctx->event, POLLIN);
248 
249 	pthread_mutex_lock(&default_context_lock);
250 	if (usbi_default_context == NULL) {
251 		usbi_default_context = ctx;
252 	}
253 	pthread_mutex_unlock(&default_context_lock);
254 
255 	if (context)
256 		*context = ctx;
257 
258 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_INFO, "libusb_init complete");
259 
260 	signal(SIGPIPE, SIG_IGN);
261 
262 	return (0);
263 }
264 
265 void
libusb_exit(libusb_context * ctx)266 libusb_exit(libusb_context *ctx)
267 {
268 	ctx = GET_CONTEXT(ctx);
269 
270 	if (ctx == NULL)
271 		return;
272 
273 	/* stop hotplug thread, if any */
274 
275 	if (ctx->hotplug_handler != NO_THREAD) {
276 		pthread_t td;
277 		void *ptr;
278 
279 		HOTPLUG_LOCK(ctx);
280 		td = ctx->hotplug_handler;
281 		ctx->hotplug_handler = NO_THREAD;
282 		if (ctx->usb_event_mode == usb_event_devd) {
283 			close(ctx->devd_pipe);
284 			ctx->devd_pipe = -1;
285 		} else if (ctx->usb_event_mode == usb_event_netlink) {
286 			close(ctx->ss.fd);
287 			ctx->ss.fd = -1;
288 		}
289 		HOTPLUG_UNLOCK(ctx);
290 
291 		pthread_join(td, &ptr);
292 	}
293 
294 	/* XXX cleanup devices */
295 
296 	libusb10_remove_pollfd(ctx, &ctx->ctx_poll);
297 	close(ctx->event);
298 	pthread_mutex_destroy(&ctx->ctx_lock);
299 	pthread_mutex_destroy(&ctx->hotplug_lock);
300 	pthread_cond_destroy(&ctx->ctx_cond);
301 
302 	pthread_mutex_lock(&default_context_lock);
303 	if (ctx == usbi_default_context) {
304 		usbi_default_context = NULL;
305 	}
306 	pthread_mutex_unlock(&default_context_lock);
307 
308 	free(ctx);
309 }
310 
311 /* Device handling and initialisation. */
312 
313 ssize_t
libusb_get_device_list(libusb_context * ctx,libusb_device *** list)314 libusb_get_device_list(libusb_context *ctx, libusb_device ***list)
315 {
316 	struct libusb20_backend *usb_backend;
317 	struct libusb20_device *pdev, *parent_dev;
318 	struct libusb_device *dev;
319 	int i, j, k;
320 
321 	ctx = GET_CONTEXT(ctx);
322 
323 	if (ctx == NULL)
324 		return (LIBUSB_ERROR_INVALID_PARAM);
325 
326 	if (list == NULL)
327 		return (LIBUSB_ERROR_INVALID_PARAM);
328 
329 	usb_backend = libusb20_be_alloc_default();
330 	if (usb_backend == NULL)
331 		return (LIBUSB_ERROR_NO_MEM);
332 
333 	/* figure out how many USB devices are present */
334 	pdev = NULL;
335 	i = 0;
336 	while ((pdev = libusb20_be_device_foreach(usb_backend, pdev)))
337 		i++;
338 
339 	/* allocate device pointer list */
340 	*list = malloc((i + 1) * sizeof(void *));
341 	if (*list == NULL) {
342 		libusb20_be_free(usb_backend);
343 		return (LIBUSB_ERROR_NO_MEM);
344 	}
345 	/* create libusb v1.0 compliant devices */
346 	i = 0;
347 	while ((pdev = libusb20_be_device_foreach(usb_backend, NULL))) {
348 
349 		dev = malloc(sizeof(*dev));
350 		if (dev == NULL) {
351 			while (i != 0) {
352 				libusb_unref_device((*list)[i - 1]);
353 				i--;
354 			}
355 			free(*list);
356 			*list = NULL;
357 			libusb20_be_free(usb_backend);
358 			return (LIBUSB_ERROR_NO_MEM);
359 		}
360 		/* get device into libUSB v1.0 list */
361 		libusb20_be_dequeue_device(usb_backend, pdev);
362 
363 		memset(dev, 0, sizeof(*dev));
364 
365 		/* init transfer queues */
366 		TAILQ_INIT(&dev->tr_head);
367 
368 		/* set context we belong to */
369 		dev->ctx = ctx;
370 
371 		/* assume we have no parent by default */
372 		dev->parent_dev = NULL;
373 
374 		/* link together the two structures */
375 		dev->os_priv = pdev;
376 		pdev->privLuData = dev;
377 
378 		(*list)[i] = libusb_ref_device(dev);
379 		i++;
380 	}
381 	(*list)[i] = NULL;
382 
383 	/* for each device, find its parent */
384 	for (j = 0; j < i; j++) {
385 		pdev = (*list)[j]->os_priv;
386 
387 		for (k = 0; k < i; k++) {
388 			if (k == j)
389 				continue;
390 
391 			parent_dev = (*list)[k]->os_priv;
392 
393 			if (parent_dev->bus_number != pdev->bus_number)
394 				continue;
395 			if (parent_dev->device_address == pdev->parent_address) {
396 				(*list)[j]->parent_dev = libusb_ref_device((*list)[k]);
397 				break;
398 			}
399 		}
400 	}
401 
402 	libusb20_be_free(usb_backend);
403 	return (i);
404 }
405 
406 void
libusb_free_device_list(libusb_device ** list,int unref_devices)407 libusb_free_device_list(libusb_device **list, int unref_devices)
408 {
409 	int i;
410 
411 	if (list == NULL)
412 		return;			/* be NULL safe */
413 
414 	if (unref_devices) {
415 		for (i = 0; list[i] != NULL; i++)
416 			libusb_unref_device(list[i]);
417 	}
418 	free(list);
419 }
420 
421 uint8_t
libusb_get_bus_number(libusb_device * dev)422 libusb_get_bus_number(libusb_device *dev)
423 {
424 	if (dev == NULL)
425 		return (0);		/* should not happen */
426 	return (libusb20_dev_get_bus_number(dev->os_priv));
427 }
428 
429 uint8_t
libusb_get_port_number(libusb_device * dev)430 libusb_get_port_number(libusb_device *dev)
431 {
432 	if (dev == NULL)
433 		return (0);		/* should not happen */
434 	return (libusb20_dev_get_parent_port(dev->os_priv));
435 }
436 
437 int
libusb_get_port_numbers(libusb_device * dev,uint8_t * buf,uint8_t bufsize)438 libusb_get_port_numbers(libusb_device *dev, uint8_t *buf, uint8_t bufsize)
439 {
440 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
441 }
442 
443 int
libusb_get_port_path(libusb_context * ctx,libusb_device * dev,uint8_t * buf,uint8_t bufsize)444 libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t *buf,
445     uint8_t bufsize)
446 {
447 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
448 }
449 
450 uint8_t
libusb_get_device_address(libusb_device * dev)451 libusb_get_device_address(libusb_device *dev)
452 {
453 	if (dev == NULL)
454 		return (0);		/* should not happen */
455 	return (libusb20_dev_get_address(dev->os_priv));
456 }
457 
458 enum libusb_speed
libusb_get_device_speed(libusb_device * dev)459 libusb_get_device_speed(libusb_device *dev)
460 {
461 	if (dev == NULL)
462 		return (LIBUSB_SPEED_UNKNOWN);	/* should not happen */
463 
464 	switch (libusb20_dev_get_speed(dev->os_priv)) {
465 	case LIBUSB20_SPEED_LOW:
466 		return (LIBUSB_SPEED_LOW);
467 	case LIBUSB20_SPEED_FULL:
468 		return (LIBUSB_SPEED_FULL);
469 	case LIBUSB20_SPEED_HIGH:
470 		return (LIBUSB_SPEED_HIGH);
471 	case LIBUSB20_SPEED_SUPER:
472 		return (LIBUSB_SPEED_SUPER);
473 	case LIBUSB20_SPEED_SUPER_PLUS:
474 		return (LIBUSB_SPEED_SUPER_PLUS);
475 	default:
476 		break;
477 	}
478 	return (LIBUSB_SPEED_UNKNOWN);
479 }
480 
481 int
libusb_get_max_packet_size(libusb_device * dev,uint8_t endpoint)482 libusb_get_max_packet_size(libusb_device *dev, uint8_t endpoint)
483 {
484 	struct libusb_config_descriptor *pdconf;
485 	struct libusb_interface *pinf;
486 	struct libusb_interface_descriptor *pdinf;
487 	struct libusb_endpoint_descriptor *pdend;
488 	int i;
489 	int j;
490 	int k;
491 	int ret;
492 
493 	if (dev == NULL)
494 		return (LIBUSB_ERROR_NO_DEVICE);
495 
496 	ret = libusb_get_active_config_descriptor(dev, &pdconf);
497 	if (ret < 0)
498 		return (ret);
499 
500 	ret = LIBUSB_ERROR_NOT_FOUND;
501 	for (i = 0; i < pdconf->bNumInterfaces; i++) {
502 		pinf = &pdconf->interface[i];
503 		for (j = 0; j < pinf->num_altsetting; j++) {
504 			pdinf = &pinf->altsetting[j];
505 			for (k = 0; k < pdinf->bNumEndpoints; k++) {
506 				pdend = &pdinf->endpoint[k];
507 				if (pdend->bEndpointAddress == endpoint) {
508 					ret = pdend->wMaxPacketSize;
509 					goto out;
510 				}
511 			}
512 		}
513 	}
514 
515 out:
516 	libusb_free_config_descriptor(pdconf);
517 	return (ret);
518 }
519 
520 int
libusb_get_max_iso_packet_size(libusb_device * dev,uint8_t endpoint)521 libusb_get_max_iso_packet_size(libusb_device *dev, uint8_t endpoint)
522 {
523 	int multiplier;
524 	int ret;
525 
526 	ret = libusb_get_max_packet_size(dev, endpoint);
527 
528 	switch (libusb20_dev_get_speed(dev->os_priv)) {
529 	case LIBUSB20_SPEED_LOW:
530 	case LIBUSB20_SPEED_FULL:
531 		break;
532 	default:
533 		if (ret > -1) {
534 			multiplier = (1 + ((ret >> 11) & 3));
535 			if (multiplier > 3)
536 				multiplier = 3;
537 			ret = (ret & 0x7FF) * multiplier;
538 		}
539 		break;
540 	}
541 	return (ret);
542 }
543 
544 libusb_device *
libusb_ref_device(libusb_device * dev)545 libusb_ref_device(libusb_device *dev)
546 {
547 	if (dev == NULL)
548 		return (NULL);		/* be NULL safe */
549 
550 	CTX_LOCK(dev->ctx);
551 	dev->refcnt++;
552 	CTX_UNLOCK(dev->ctx);
553 
554 	return (dev);
555 }
556 
557 void
libusb_unref_device(libusb_device * dev)558 libusb_unref_device(libusb_device *dev)
559 {
560 	if (dev == NULL)
561 		return;			/* be NULL safe */
562 
563 	CTX_LOCK(dev->ctx);
564 	dev->refcnt--;
565 	CTX_UNLOCK(dev->ctx);
566 
567 	if (dev->refcnt == 0) {
568 		libusb_unref_device(dev->parent_dev);
569 		libusb20_dev_free(dev->os_priv);
570 		free(dev);
571 	}
572 }
573 
574 int
libusb_open(libusb_device * dev,libusb_device_handle ** devh)575 libusb_open(libusb_device *dev, libusb_device_handle **devh)
576 {
577 	libusb_context *ctx = dev->ctx;
578 	struct libusb20_device *pdev = dev->os_priv;
579 	int err;
580 
581 	if (devh == NULL)
582 		return (LIBUSB_ERROR_INVALID_PARAM);
583 
584 	/* set default device handle value */
585 	*devh = NULL;
586 
587 	dev = libusb_ref_device(dev);
588 	if (dev == NULL)
589 		return (LIBUSB_ERROR_INVALID_PARAM);
590 
591 	err = libusb20_dev_open(pdev, LIBUSB_NUM_SW_ENDPOINTS);
592 	if (err) {
593 		libusb_unref_device(dev);
594 		return (LIBUSB_ERROR_NO_MEM);
595 	}
596 
597 	/*
598 	 * Clear the device gone flag, in case the device was opened
599 	 * after a re-attach, to allow new transaction:
600 	 */
601 	CTX_LOCK(ctx);
602 	dev->device_is_gone = 0;
603 	CTX_UNLOCK(ctx);
604 
605 	libusb10_add_pollfd(ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
606 	    POLLOUT | POLLRDNORM | POLLWRNORM);
607 
608 	/* make sure our event loop detects the new device */
609 	libusb_interrupt_event_handler(ctx);
610 
611 	*devh = pdev;
612 
613 	return (0);
614 }
615 
616 libusb_device_handle *
libusb_open_device_with_vid_pid(libusb_context * ctx,uint16_t vendor_id,uint16_t product_id)617 libusb_open_device_with_vid_pid(libusb_context *ctx, uint16_t vendor_id,
618     uint16_t product_id)
619 {
620 	struct libusb_device **devs;
621 	struct libusb20_device *pdev;
622 	struct LIBUSB20_DEVICE_DESC_DECODED *pdesc;
623 	int i;
624 	int j;
625 
626 	ctx = GET_CONTEXT(ctx);
627 	if (ctx == NULL)
628 		return (NULL);		/* be NULL safe */
629 
630 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_open_device_with_vid_pid enter");
631 
632 	if ((i = libusb_get_device_list(ctx, &devs)) < 0)
633 		return (NULL);
634 
635 	pdev = NULL;
636 	for (j = 0; j < i; j++) {
637 		struct libusb20_device *tdev;
638 
639 		tdev = devs[j]->os_priv;
640 		pdesc = libusb20_dev_get_device_desc(tdev);
641 		/*
642 		 * NOTE: The USB library will automatically swap the
643 		 * fields in the device descriptor to be of host
644 		 * endian type!
645 		 */
646 		if (pdesc->idVendor == vendor_id &&
647 		    pdesc->idProduct == product_id) {
648 			libusb_open(devs[j], &pdev);
649 			break;
650 		}
651 	}
652 
653 	libusb_free_device_list(devs, 1);
654 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_open_device_with_vid_pid leave");
655 	return (pdev);
656 }
657 
658 void
libusb_close(struct libusb20_device * pdev)659 libusb_close(struct libusb20_device *pdev)
660 {
661 	libusb_context *ctx;
662 	struct libusb_device *dev;
663 
664 	if (pdev == NULL)
665 		return;			/* be NULL safe */
666 
667 	dev = libusb_get_device(pdev);
668 	ctx = dev->ctx;
669 
670 	libusb10_remove_pollfd(ctx, &dev->dev_poll);
671 
672 	libusb20_dev_close(pdev);
673 
674 	/* unref will free the "pdev" when the refcount reaches zero */
675 	libusb_unref_device(dev);
676 
677 	/* make sure our event loop detects the closed device */
678 	libusb_interrupt_event_handler(ctx);
679 }
680 
681 libusb_device *
libusb_get_device(struct libusb20_device * pdev)682 libusb_get_device(struct libusb20_device *pdev)
683 {
684 	if (pdev == NULL)
685 		return (NULL);
686 	return ((libusb_device *)pdev->privLuData);
687 }
688 
689 int
libusb_get_configuration(struct libusb20_device * pdev,int * config)690 libusb_get_configuration(struct libusb20_device *pdev, int *config)
691 {
692 	struct libusb20_config *pconf;
693 
694 	if (pdev == NULL || config == NULL)
695 		return (LIBUSB_ERROR_INVALID_PARAM);
696 
697 	pconf = libusb20_dev_alloc_config(pdev, libusb20_dev_get_config_index(pdev));
698 	if (pconf == NULL)
699 		return (LIBUSB_ERROR_NO_MEM);
700 
701 	*config = pconf->desc.bConfigurationValue;
702 
703 	free(pconf);
704 
705 	return (0);
706 }
707 
708 int
libusb_set_configuration(struct libusb20_device * pdev,int configuration)709 libusb_set_configuration(struct libusb20_device *pdev, int configuration)
710 {
711 	struct libusb20_config *pconf;
712 	struct libusb_device *dev;
713 	int err;
714 	uint8_t i;
715 
716 	dev = libusb_get_device(pdev);
717 	if (dev == NULL)
718 		return (LIBUSB_ERROR_INVALID_PARAM);
719 
720 	if (configuration < 1) {
721 		/* unconfigure */
722 		i = 255;
723 	} else {
724 		for (i = 0; i != 255; i++) {
725 			uint8_t found;
726 
727 			pconf = libusb20_dev_alloc_config(pdev, i);
728 			if (pconf == NULL)
729 				return (LIBUSB_ERROR_INVALID_PARAM);
730 			found = (pconf->desc.bConfigurationValue
731 			    == configuration);
732 			free(pconf);
733 
734 			if (found)
735 				goto set_config;
736 		}
737 		return (LIBUSB_ERROR_INVALID_PARAM);
738 	}
739 
740 set_config:
741 
742 	libusb10_cancel_all_transfer(dev);
743 
744 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
745 
746 	err = libusb20_dev_set_config_index(pdev, i);
747 
748 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
749 	    POLLOUT | POLLRDNORM | POLLWRNORM);
750 
751 	return (err ? LIBUSB_ERROR_INVALID_PARAM : 0);
752 }
753 
754 int
libusb_claim_interface(struct libusb20_device * pdev,int interface_number)755 libusb_claim_interface(struct libusb20_device *pdev, int interface_number)
756 {
757 	libusb_device *dev;
758 	int err = 0;
759 
760 	dev = libusb_get_device(pdev);
761 	if (dev == NULL)
762 		return (LIBUSB_ERROR_INVALID_PARAM);
763 
764 	if (interface_number < 0 || interface_number > 31)
765 		return (LIBUSB_ERROR_INVALID_PARAM);
766 
767 	if (pdev->auto_detach != 0) {
768 		err = libusb_detach_kernel_driver(pdev, interface_number);
769 		if (err != 0)
770 			goto done;
771 	}
772 
773 	CTX_LOCK(dev->ctx);
774 	dev->claimed_interfaces |= (1 << interface_number);
775 	CTX_UNLOCK(dev->ctx);
776 done:
777 	return (err);
778 }
779 
780 int
libusb_release_interface(struct libusb20_device * pdev,int interface_number)781 libusb_release_interface(struct libusb20_device *pdev, int interface_number)
782 {
783 	libusb_device *dev;
784 	int err = 0;
785 
786 	dev = libusb_get_device(pdev);
787 	if (dev == NULL)
788 		return (LIBUSB_ERROR_INVALID_PARAM);
789 
790 	if (interface_number < 0 || interface_number > 31)
791 		return (LIBUSB_ERROR_INVALID_PARAM);
792 
793 	if (pdev->auto_detach != 0) {
794 		err = libusb_attach_kernel_driver(pdev, interface_number);
795 		if (err != 0)
796 			goto done;
797 	}
798 
799 	CTX_LOCK(dev->ctx);
800 	if (!(dev->claimed_interfaces & (1 << interface_number)))
801 		err = LIBUSB_ERROR_NOT_FOUND;
802 	else
803 		dev->claimed_interfaces &= ~(1 << interface_number);
804 	CTX_UNLOCK(dev->ctx);
805 done:
806 	return (err);
807 }
808 
809 int
libusb_set_interface_alt_setting(struct libusb20_device * pdev,int interface_number,int alternate_setting)810 libusb_set_interface_alt_setting(struct libusb20_device *pdev,
811     int interface_number, int alternate_setting)
812 {
813 	libusb_device *dev;
814 	int err = 0;
815 
816 	dev = libusb_get_device(pdev);
817 	if (dev == NULL)
818 		return (LIBUSB_ERROR_INVALID_PARAM);
819 
820 	if (interface_number < 0 || interface_number > 31)
821 		return (LIBUSB_ERROR_INVALID_PARAM);
822 
823 	CTX_LOCK(dev->ctx);
824 	if (!(dev->claimed_interfaces & (1 << interface_number)))
825 		err = LIBUSB_ERROR_NOT_FOUND;
826 	CTX_UNLOCK(dev->ctx);
827 
828 	if (err)
829 		return (err);
830 
831 	libusb10_cancel_all_transfer(dev);
832 
833 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
834 
835 	err = libusb20_dev_set_alt_index(pdev,
836 	    interface_number, alternate_setting);
837 
838 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
839 	    pdev, libusb20_dev_get_fd(pdev),
840 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
841 
842 	return (err ? LIBUSB_ERROR_OTHER : 0);
843 }
844 
845 libusb_device *
libusb_get_parent(libusb_device * dev)846 libusb_get_parent(libusb_device *dev)
847 {
848 	return (dev->parent_dev);
849 }
850 
851 static struct libusb20_transfer *
libusb10_get_transfer(struct libusb20_device * pdev,uint8_t endpoint,uint8_t xfer_index)852 libusb10_get_transfer(struct libusb20_device *pdev,
853     uint8_t endpoint, uint8_t xfer_index)
854 {
855 	xfer_index &= 1;	/* double buffering */
856 
857 	xfer_index |= (endpoint & LIBUSB20_ENDPOINT_ADDRESS_MASK) * 4;
858 
859 	if (endpoint & LIBUSB20_ENDPOINT_DIR_MASK) {
860 		/* this is an IN endpoint */
861 		xfer_index |= 2;
862 	}
863 	return (libusb20_tr_get_pointer(pdev, xfer_index));
864 }
865 
866 int
libusb_clear_halt(struct libusb20_device * pdev,uint8_t endpoint)867 libusb_clear_halt(struct libusb20_device *pdev, uint8_t endpoint)
868 {
869 	struct libusb20_transfer *xfer;
870 	struct libusb_device *dev;
871 	int err;
872 
873 	xfer = libusb10_get_transfer(pdev, endpoint, 0);
874 	if (xfer == NULL)
875 		return (LIBUSB_ERROR_INVALID_PARAM);
876 
877 	dev = libusb_get_device(pdev);
878 	if (dev == NULL)
879 		return (LIBUSB_ERROR_INVALID_PARAM);
880 
881 	CTX_LOCK(dev->ctx);
882 	err = libusb20_tr_open(xfer, 0, 1, endpoint);
883 	CTX_UNLOCK(dev->ctx);
884 
885 	if (err != 0 && err != LIBUSB20_ERROR_BUSY)
886 		return (LIBUSB_ERROR_OTHER);
887 
888 	libusb20_tr_clear_stall_sync(xfer);
889 
890 	/* check if we opened the transfer */
891 	if (err == 0) {
892 		CTX_LOCK(dev->ctx);
893 		libusb20_tr_close(xfer);
894 		CTX_UNLOCK(dev->ctx);
895 	}
896 	return (0);			/* success */
897 }
898 
899 int
libusb_reset_device(struct libusb20_device * pdev)900 libusb_reset_device(struct libusb20_device *pdev)
901 {
902 	libusb_device *dev;
903 	int err;
904 
905 	dev = libusb_get_device(pdev);
906 	if (dev == NULL)
907 		return (LIBUSB_ERROR_INVALID_PARAM);
908 
909 	libusb10_cancel_all_transfer(dev);
910 
911 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
912 
913 	err = libusb20_dev_reset(pdev);
914 
915 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
916 	    pdev, libusb20_dev_get_fd(pdev),
917 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
918 
919 	return (err ? LIBUSB_ERROR_OTHER : 0);
920 }
921 
922 int
libusb_check_connected(struct libusb20_device * pdev)923 libusb_check_connected(struct libusb20_device *pdev)
924 {
925 	libusb_device *dev;
926 	int err;
927 
928 	dev = libusb_get_device(pdev);
929 	if (dev == NULL)
930 		return (LIBUSB_ERROR_INVALID_PARAM);
931 
932 	err = libusb20_dev_check_connected(pdev);
933 
934 	return (err ? LIBUSB_ERROR_NO_DEVICE : 0);
935 }
936 
937 int
libusb_kernel_driver_active(struct libusb20_device * pdev,int interface)938 libusb_kernel_driver_active(struct libusb20_device *pdev, int interface)
939 {
940 	if (pdev == NULL)
941 		return (LIBUSB_ERROR_INVALID_PARAM);
942 
943 	if (libusb20_dev_kernel_driver_active(pdev, interface))
944 		return (0);		/* no kernel driver is active */
945 	else
946 		return (1);		/* kernel driver is active */
947 }
948 
949 int
libusb_get_driver_np(struct libusb20_device * pdev,int interface,char * name,int namelen)950 libusb_get_driver_np(struct libusb20_device *pdev, int interface,
951     char *name, int namelen)
952 {
953 	return (libusb_get_driver(pdev, interface, name, namelen));
954 }
955 
956 int
libusb_get_driver(struct libusb20_device * pdev,int interface,char * name,int namelen)957 libusb_get_driver(struct libusb20_device *pdev, int interface,
958     char *name, int namelen)
959 {
960 	char *ptr;
961 	int err;
962 
963 	if (pdev == NULL)
964 		return (LIBUSB_ERROR_INVALID_PARAM);
965 	if (namelen < 1)
966 		return (LIBUSB_ERROR_INVALID_PARAM);
967 	if (namelen > 255)
968 		namelen = 255;
969 
970 	err = libusb20_dev_get_iface_desc(
971 	    pdev, interface, name, namelen);
972 
973 	if (err != 0)
974 		return (LIBUSB_ERROR_OTHER);
975 
976 	/* we only want the driver name */
977 	ptr = strstr(name, ":");
978 	if (ptr != NULL)
979 		*ptr = 0;
980 
981 	return (0);
982 }
983 
984 int
libusb_detach_kernel_driver_np(struct libusb20_device * pdev,int interface)985 libusb_detach_kernel_driver_np(struct libusb20_device *pdev, int interface)
986 {
987 	return (libusb_detach_kernel_driver(pdev, interface));
988 }
989 
990 int
libusb_detach_kernel_driver(struct libusb20_device * pdev,int interface)991 libusb_detach_kernel_driver(struct libusb20_device *pdev, int interface)
992 {
993 	int err;
994 
995 	if (pdev == NULL)
996 		return (LIBUSB_ERROR_INVALID_PARAM);
997 
998 	err = libusb20_dev_detach_kernel_driver(
999 	    pdev, interface);
1000 
1001 	return (err ? LIBUSB_ERROR_OTHER : 0);
1002 }
1003 
1004 int
libusb_attach_kernel_driver(struct libusb20_device * pdev,int interface)1005 libusb_attach_kernel_driver(struct libusb20_device *pdev, int interface)
1006 {
1007 	if (pdev == NULL)
1008 		return (LIBUSB_ERROR_INVALID_PARAM);
1009 	/* stub - currently not supported by libusb20 */
1010 	return (0);
1011 }
1012 
1013 int
libusb_set_auto_detach_kernel_driver(libusb_device_handle * dev,int enable)1014 libusb_set_auto_detach_kernel_driver(libusb_device_handle *dev, int enable)
1015 {
1016 	dev->auto_detach = (enable ? 1 : 0);
1017 	return (0);
1018 }
1019 
1020 /* Asynchronous device I/O */
1021 
1022 struct libusb_transfer *
libusb_alloc_transfer(int iso_packets)1023 libusb_alloc_transfer(int iso_packets)
1024 {
1025 	struct libusb_transfer *uxfer;
1026 	struct libusb_super_transfer *sxfer;
1027 	int len;
1028 
1029 	len = sizeof(struct libusb_transfer) +
1030 	    sizeof(struct libusb_super_transfer) +
1031 	    (iso_packets * sizeof(libusb_iso_packet_descriptor));
1032 
1033 	sxfer = malloc(len);
1034 	if (sxfer == NULL)
1035 		return (NULL);
1036 
1037 	memset(sxfer, 0, len);
1038 
1039 	uxfer = (struct libusb_transfer *)(
1040 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1041 
1042 	/* set default value */
1043 	uxfer->num_iso_packets = iso_packets;
1044 
1045 	return (uxfer);
1046 }
1047 
1048 void
libusb_free_transfer(struct libusb_transfer * uxfer)1049 libusb_free_transfer(struct libusb_transfer *uxfer)
1050 {
1051 	struct libusb_super_transfer *sxfer;
1052 
1053 	if (uxfer == NULL)
1054 		return;			/* be NULL safe */
1055 
1056 	/* check if we should free the transfer buffer */
1057 	if (uxfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
1058 		free(uxfer->buffer);
1059 
1060 	sxfer = (struct libusb_super_transfer *)(
1061 	    (uint8_t *)uxfer - sizeof(*sxfer));
1062 
1063 	free(sxfer);
1064 }
1065 
1066 static uint32_t
libusb10_get_maxframe(struct libusb20_device * pdev,libusb_transfer * xfer)1067 libusb10_get_maxframe(struct libusb20_device *pdev, libusb_transfer *xfer)
1068 {
1069 	uint32_t ret;
1070 
1071 	switch (xfer->type) {
1072 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1073 		ret = 60 | LIBUSB20_MAX_FRAME_PRE_SCALE;	/* 60ms */
1074 		break;
1075 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1076 		ret = 2;
1077 		break;
1078 	default:
1079 		ret = 1;
1080 		break;
1081 	}
1082 	return (ret);
1083 }
1084 
1085 static int
libusb10_get_buffsize(struct libusb20_device * pdev,libusb_transfer * xfer)1086 libusb10_get_buffsize(struct libusb20_device *pdev, libusb_transfer *xfer)
1087 {
1088 	int ret;
1089 	int usb_speed;
1090 
1091 	usb_speed = libusb20_dev_get_speed(pdev);
1092 
1093 	switch (xfer->type) {
1094 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1095 		ret = 0;		/* kernel will auto-select */
1096 		break;
1097 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1098 		ret = 1024;
1099 		break;
1100 	default:
1101 		switch (usb_speed) {
1102 		case LIBUSB20_SPEED_LOW:
1103 			ret = 256;
1104 			break;
1105 		case LIBUSB20_SPEED_FULL:
1106 			ret = 4096;
1107 			break;
1108 		case LIBUSB20_SPEED_SUPER:
1109 			ret = 65536;
1110 			break;
1111 		case LIBUSB20_SPEED_SUPER_PLUS:
1112 			ret = 131072;
1113 			break;
1114 		default:
1115 			ret = 16384;
1116 			break;
1117 		}
1118 		break;
1119 	}
1120 	return (ret);
1121 }
1122 
1123 static int
libusb10_convert_error(uint8_t status)1124 libusb10_convert_error(uint8_t status)
1125 {
1126 	;				/* indent fix */
1127 
1128 	switch (status) {
1129 	case LIBUSB20_TRANSFER_START:
1130 	case LIBUSB20_TRANSFER_COMPLETED:
1131 		return (LIBUSB_TRANSFER_COMPLETED);
1132 	case LIBUSB20_TRANSFER_OVERFLOW:
1133 		return (LIBUSB_TRANSFER_OVERFLOW);
1134 	case LIBUSB20_TRANSFER_NO_DEVICE:
1135 		return (LIBUSB_TRANSFER_NO_DEVICE);
1136 	case LIBUSB20_TRANSFER_STALL:
1137 		return (LIBUSB_TRANSFER_STALL);
1138 	case LIBUSB20_TRANSFER_CANCELLED:
1139 		return (LIBUSB_TRANSFER_CANCELLED);
1140 	case LIBUSB20_TRANSFER_TIMED_OUT:
1141 		return (LIBUSB_TRANSFER_TIMED_OUT);
1142 	default:
1143 		return (LIBUSB_TRANSFER_ERROR);
1144 	}
1145 }
1146 
1147 /* This function must be called locked */
1148 
1149 static void
libusb10_complete_transfer(struct libusb20_transfer * pxfer,struct libusb_super_transfer * sxfer,int status)1150 libusb10_complete_transfer(struct libusb20_transfer *pxfer,
1151     struct libusb_super_transfer *sxfer, int status)
1152 {
1153 	struct libusb_transfer *uxfer;
1154 	struct libusb_device *dev;
1155 
1156 	uxfer = (struct libusb_transfer *)(
1157 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1158 
1159 	if (pxfer != NULL)
1160 		libusb20_tr_set_priv_sc1(pxfer, NULL);
1161 
1162 	/* set transfer status */
1163 	uxfer->status = status;
1164 
1165 	/* update super transfer state */
1166 	sxfer->state = LIBUSB_SUPER_XFER_ST_NONE;
1167 
1168 	dev = libusb_get_device(uxfer->dev_handle);
1169 
1170 	TAILQ_INSERT_TAIL(&dev->ctx->tr_done, sxfer, entry);
1171 }
1172 
1173 /* This function must be called locked */
1174 
1175 static void
libusb10_isoc_proxy(struct libusb20_transfer * pxfer)1176 libusb10_isoc_proxy(struct libusb20_transfer *pxfer)
1177 {
1178 	struct libusb_super_transfer *sxfer;
1179 	struct libusb_transfer *uxfer;
1180 	uint32_t actlen;
1181 	uint16_t iso_packets;
1182 	uint16_t i;
1183 	uint8_t status;
1184 
1185 	status = libusb20_tr_get_status(pxfer);
1186 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1187 	actlen = libusb20_tr_get_actual_length(pxfer);
1188 	iso_packets = libusb20_tr_get_max_frames(pxfer);
1189 
1190 	if (sxfer == NULL)
1191 		return; /* cancelled - nothing to do */
1192 
1193 	uxfer = (struct libusb_transfer *)(
1194 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1195 
1196 	if (iso_packets > uxfer->num_iso_packets)
1197 		iso_packets = uxfer->num_iso_packets;
1198 
1199 	if (iso_packets == 0)
1200 		return; /* nothing to do */
1201 
1202 	/* make sure that the number of ISOCHRONOUS packets is valid */
1203 	uxfer->num_iso_packets = iso_packets;
1204 
1205 	switch (status) {
1206 	case LIBUSB20_TRANSFER_COMPLETED:
1207 		/* update actual length */
1208 		uxfer->actual_length = actlen;
1209 		for (i = 0; i != iso_packets; i++) {
1210 			uxfer->iso_packet_desc[i].actual_length =
1211 			    libusb20_tr_get_length(pxfer, i);
1212 		}
1213 		libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1214 		break;
1215 	case LIBUSB20_TRANSFER_START:
1216 		/* setup length(s) */
1217 		actlen = 0;
1218 		for (i = 0; i != iso_packets; i++) {
1219 			libusb20_tr_setup_isoc(pxfer,
1220 			    &uxfer->buffer[actlen],
1221 			    uxfer->iso_packet_desc[i].length, i);
1222 			actlen += uxfer->iso_packet_desc[i].length;
1223 		}
1224 
1225 		/* no remainder */
1226 		sxfer->rem_len = 0;
1227 
1228 		libusb20_tr_set_total_frames(pxfer, iso_packets);
1229 		libusb20_tr_submit(pxfer);
1230 
1231 		/* fork another USB transfer, if any */
1232 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1233 		break;
1234 	default:
1235 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1236 		break;
1237 	}
1238 }
1239 
1240 /* This function must be called locked */
1241 
1242 static void
libusb10_bulk_intr_proxy(struct libusb20_transfer * pxfer)1243 libusb10_bulk_intr_proxy(struct libusb20_transfer *pxfer)
1244 {
1245 	struct libusb_super_transfer *sxfer;
1246 	struct libusb_transfer *uxfer;
1247 	uint32_t max_bulk;
1248 	uint32_t actlen;
1249 	uint8_t status;
1250 	uint8_t flags;
1251 
1252 	status = libusb20_tr_get_status(pxfer);
1253 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1254 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1255 	actlen = libusb20_tr_get_actual_length(pxfer);
1256 
1257 	if (sxfer == NULL)
1258 		return;			/* cancelled - nothing to do */
1259 
1260 	uxfer = (struct libusb_transfer *)(
1261 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1262 
1263 	flags = uxfer->flags;
1264 
1265 	switch (status) {
1266 	case LIBUSB20_TRANSFER_COMPLETED:
1267 
1268 		uxfer->actual_length += actlen;
1269 
1270 		/* check for short packet */
1271 		if (sxfer->last_len != actlen) {
1272 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1273 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1274 			} else {
1275 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1276 			}
1277 			break;
1278 		}
1279 		/* check for end of data */
1280 		if (sxfer->rem_len == 0) {
1281 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1282 			break;
1283 		}
1284 		/* FALLTHROUGH */
1285 
1286 	case LIBUSB20_TRANSFER_START:
1287 		if (max_bulk > sxfer->rem_len) {
1288 			max_bulk = sxfer->rem_len;
1289 		}
1290 		/* setup new BULK or INTERRUPT transaction */
1291 		libusb20_tr_setup_bulk(pxfer,
1292 		    sxfer->curr_data, max_bulk, uxfer->timeout);
1293 
1294 		/* update counters */
1295 		sxfer->last_len = max_bulk;
1296 		sxfer->curr_data += max_bulk;
1297 		sxfer->rem_len -= max_bulk;
1298 
1299 		libusb20_tr_submit(pxfer);
1300 
1301 		/* check if we can fork another USB transfer */
1302 		if (sxfer->rem_len == 0)
1303 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1304 		break;
1305 
1306 	default:
1307 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1308 		break;
1309 	}
1310 }
1311 
1312 /* This function must be called locked */
1313 
1314 static void
libusb10_ctrl_proxy(struct libusb20_transfer * pxfer)1315 libusb10_ctrl_proxy(struct libusb20_transfer *pxfer)
1316 {
1317 	struct libusb_super_transfer *sxfer;
1318 	struct libusb_transfer *uxfer;
1319 	uint32_t max_bulk;
1320 	uint32_t actlen;
1321 	uint8_t status;
1322 	uint8_t flags;
1323 
1324 	status = libusb20_tr_get_status(pxfer);
1325 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1326 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1327 	actlen = libusb20_tr_get_actual_length(pxfer);
1328 
1329 	if (sxfer == NULL)
1330 		return;			/* cancelled - nothing to do */
1331 
1332 	uxfer = (struct libusb_transfer *)(
1333 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1334 
1335 	flags = uxfer->flags;
1336 
1337 	switch (status) {
1338 	case LIBUSB20_TRANSFER_COMPLETED:
1339 
1340 		uxfer->actual_length += actlen;
1341 
1342 		/* subtract length of SETUP packet, if any */
1343 		actlen -= libusb20_tr_get_length(pxfer, 0);
1344 
1345 		/* check for short packet */
1346 		if (sxfer->last_len != actlen) {
1347 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1348 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1349 			} else {
1350 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1351 			}
1352 			break;
1353 		}
1354 		/* check for end of data */
1355 		if (sxfer->rem_len == 0) {
1356 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1357 			break;
1358 		}
1359 		/* FALLTHROUGH */
1360 
1361 	case LIBUSB20_TRANSFER_START:
1362 		if (max_bulk > sxfer->rem_len) {
1363 			max_bulk = sxfer->rem_len;
1364 		}
1365 		/* setup new CONTROL transaction */
1366 		if (status == LIBUSB20_TRANSFER_COMPLETED) {
1367 			/* next fragment - don't send SETUP packet */
1368 			libusb20_tr_set_length(pxfer, 0, 0);
1369 		} else {
1370 			/* first fragment - send SETUP packet */
1371 			libusb20_tr_set_length(pxfer, 8, 0);
1372 			libusb20_tr_set_buffer(pxfer, uxfer->buffer, 0);
1373 		}
1374 
1375 		if (max_bulk != 0) {
1376 			libusb20_tr_set_length(pxfer, max_bulk, 1);
1377 			libusb20_tr_set_buffer(pxfer, sxfer->curr_data, 1);
1378 			libusb20_tr_set_total_frames(pxfer, 2);
1379 		} else {
1380 			libusb20_tr_set_total_frames(pxfer, 1);
1381 		}
1382 
1383 		/* update counters */
1384 		sxfer->last_len = max_bulk;
1385 		sxfer->curr_data += max_bulk;
1386 		sxfer->rem_len -= max_bulk;
1387 
1388 		libusb20_tr_submit(pxfer);
1389 
1390 		/* check if we can fork another USB transfer */
1391 		if (sxfer->rem_len == 0)
1392 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1393 		break;
1394 
1395 	default:
1396 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1397 		break;
1398 	}
1399 }
1400 
1401 /* The following function must be called locked */
1402 
1403 static void
libusb10_submit_transfer_sub(struct libusb20_device * pdev,uint8_t endpoint)1404 libusb10_submit_transfer_sub(struct libusb20_device *pdev, uint8_t endpoint)
1405 {
1406 	struct libusb20_transfer *pxfer0;
1407 	struct libusb20_transfer *pxfer1;
1408 	struct libusb_super_transfer *sxfer;
1409 	struct libusb_transfer *uxfer;
1410 	struct libusb_device *dev;
1411 	int err;
1412 	int buffsize;
1413 	int maxframe;
1414 	int temp;
1415 
1416 	dev = libusb_get_device(pdev);
1417 
1418 	pxfer0 = libusb10_get_transfer(pdev, endpoint, 0);
1419 	pxfer1 = libusb10_get_transfer(pdev, endpoint, 1);
1420 
1421 	if (pxfer0 == NULL || pxfer1 == NULL)
1422 		return;			/* shouldn't happen */
1423 
1424 	temp = 0;
1425 	if (libusb20_tr_pending(pxfer0))
1426 		temp |= 1;
1427 	if (libusb20_tr_pending(pxfer1))
1428 		temp |= 2;
1429 
1430 	switch (temp) {
1431 	case 3:
1432 		/* wait till one of the transfers complete */
1433 		return;
1434 	case 2:
1435 		sxfer = libusb20_tr_get_priv_sc1(pxfer1);
1436 		if (sxfer == NULL)
1437 			return;		/* cancelling */
1438 		if (sxfer->rem_len)
1439 			return;		/* cannot queue another one */
1440 		/* swap transfers */
1441 		pxfer1 = pxfer0;
1442 		break;
1443 	case 1:
1444 		sxfer = libusb20_tr_get_priv_sc1(pxfer0);
1445 		if (sxfer == NULL)
1446 			return;		/* cancelling */
1447 		if (sxfer->rem_len)
1448 			return;		/* cannot queue another one */
1449 		/* swap transfers */
1450 		pxfer0 = pxfer1;
1451 		break;
1452 	default:
1453 		break;
1454 	}
1455 
1456 	/* find next transfer on same endpoint */
1457 	TAILQ_FOREACH(sxfer, &dev->tr_head, entry) {
1458 
1459 		uxfer = (struct libusb_transfer *)(
1460 		    ((uint8_t *)sxfer) + sizeof(*sxfer));
1461 
1462 		if (uxfer->endpoint == endpoint) {
1463 			TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1464 			sxfer->entry.tqe_prev = NULL;
1465 			goto found;
1466 		}
1467 	}
1468 	return;				/* success */
1469 
1470 found:
1471 
1472 	libusb20_tr_set_priv_sc0(pxfer0, pdev);
1473 	libusb20_tr_set_priv_sc1(pxfer0, sxfer);
1474 
1475 	/* reset super transfer state */
1476 	sxfer->rem_len = uxfer->length;
1477 	sxfer->curr_data = uxfer->buffer;
1478 	uxfer->actual_length = 0;
1479 
1480 	switch (uxfer->type) {
1481 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1482 		libusb20_tr_set_callback(pxfer0, libusb10_isoc_proxy);
1483 		break;
1484 	case LIBUSB_TRANSFER_TYPE_BULK:
1485 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1486 		libusb20_tr_set_callback(pxfer0, libusb10_bulk_intr_proxy);
1487 		break;
1488 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1489 		libusb20_tr_set_callback(pxfer0, libusb10_ctrl_proxy);
1490 		if (sxfer->rem_len < 8)
1491 			goto failure;
1492 
1493 		/* remove SETUP packet from data */
1494 		sxfer->rem_len -= 8;
1495 		sxfer->curr_data += 8;
1496 		break;
1497 	default:
1498 		goto failure;
1499 	}
1500 
1501 	buffsize = libusb10_get_buffsize(pdev, uxfer);
1502 	maxframe = libusb10_get_maxframe(pdev, uxfer);
1503 
1504 	/* make sure the transfer is opened */
1505 	err = libusb20_tr_open_stream(pxfer0, buffsize, maxframe,
1506 	    endpoint, sxfer->stream_id);
1507 	if (err && (err != LIBUSB20_ERROR_BUSY)) {
1508 		goto failure;
1509 	}
1510 	libusb20_tr_start(pxfer0);
1511 	return;
1512 
1513 failure:
1514 	libusb10_complete_transfer(pxfer0, sxfer, LIBUSB_TRANSFER_ERROR);
1515 	/* make sure our event loop spins the done handler */
1516 	libusb_interrupt_event_handler(dev->ctx);
1517 }
1518 
1519 /* The following function must be called unlocked */
1520 
1521 int
libusb_submit_transfer(struct libusb_transfer * uxfer)1522 libusb_submit_transfer(struct libusb_transfer *uxfer)
1523 {
1524 	struct libusb20_transfer *pxfer0;
1525 	struct libusb20_transfer *pxfer1;
1526 	struct libusb_super_transfer *sxfer;
1527 	struct libusb_device *dev;
1528 	uint8_t endpoint;
1529 	int err;
1530 
1531 	if (uxfer == NULL)
1532 		return (LIBUSB_ERROR_INVALID_PARAM);
1533 
1534 	if (uxfer->dev_handle == NULL)
1535 		return (LIBUSB_ERROR_INVALID_PARAM);
1536 
1537 	endpoint = uxfer->endpoint;
1538 
1539 	dev = libusb_get_device(uxfer->dev_handle);
1540 
1541 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_submit_transfer enter");
1542 
1543 	sxfer = (struct libusb_super_transfer *)(
1544 	    (uint8_t *)uxfer - sizeof(*sxfer));
1545 
1546 	CTX_LOCK(dev->ctx);
1547 
1548 	pxfer0 = libusb10_get_transfer(uxfer->dev_handle, endpoint, 0);
1549 	pxfer1 = libusb10_get_transfer(uxfer->dev_handle, endpoint, 1);
1550 
1551 	if (pxfer0 == NULL || pxfer1 == NULL) {
1552 		err = LIBUSB_ERROR_OTHER;
1553 	} else if ((sxfer->entry.tqe_prev != NULL) ||
1554 	    (libusb20_tr_get_priv_sc1(pxfer0) == sxfer) ||
1555 	    (libusb20_tr_get_priv_sc1(pxfer1) == sxfer)) {
1556 		err = LIBUSB_ERROR_BUSY;
1557 	} else if (dev->device_is_gone != 0) {
1558 		err = LIBUSB_ERROR_NO_DEVICE;
1559 	} else {
1560 
1561 		/* set pending state */
1562 		sxfer->state = LIBUSB_SUPER_XFER_ST_PEND;
1563 
1564 		/* insert transfer into transfer head list */
1565 		TAILQ_INSERT_TAIL(&dev->tr_head, sxfer, entry);
1566 
1567 		/* start work transfers */
1568 		libusb10_submit_transfer_sub(
1569 		    uxfer->dev_handle, endpoint);
1570 
1571 		err = 0;		/* success */
1572 	}
1573 
1574 	CTX_UNLOCK(dev->ctx);
1575 
1576 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_submit_transfer leave %d", err);
1577 
1578 	return (err);
1579 }
1580 
1581 /* Asynchronous transfer cancel */
1582 
1583 int
libusb_cancel_transfer(struct libusb_transfer * uxfer)1584 libusb_cancel_transfer(struct libusb_transfer *uxfer)
1585 {
1586 	struct libusb20_transfer *pxfer0;
1587 	struct libusb20_transfer *pxfer1;
1588 	struct libusb_super_transfer *sxfer;
1589 	struct libusb_device *dev;
1590 	struct libusb_device_handle *devh;
1591 	uint8_t endpoint;
1592 	int retval;
1593 
1594 	if (uxfer == NULL)
1595 		return (LIBUSB_ERROR_INVALID_PARAM);
1596 
1597 	/* check if not initialised */
1598 	if ((devh = uxfer->dev_handle) == NULL)
1599 		return (LIBUSB_ERROR_NOT_FOUND);
1600 
1601 	endpoint = uxfer->endpoint;
1602 
1603 	dev = libusb_get_device(devh);
1604 
1605 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_cancel_transfer enter");
1606 
1607 	sxfer = (struct libusb_super_transfer *)(
1608 	    (uint8_t *)uxfer - sizeof(*sxfer));
1609 
1610 	retval = 0;
1611 
1612 	CTX_LOCK(dev->ctx);
1613 
1614 	pxfer0 = libusb10_get_transfer(devh, endpoint, 0);
1615 	pxfer1 = libusb10_get_transfer(devh, endpoint, 1);
1616 
1617 	if (sxfer->state != LIBUSB_SUPER_XFER_ST_PEND) {
1618 		/* only update the transfer status */
1619 		uxfer->status = LIBUSB_TRANSFER_CANCELLED;
1620 		retval = LIBUSB_ERROR_NOT_FOUND;
1621 	} else if (sxfer->entry.tqe_prev != NULL) {
1622 		/* we are lucky - transfer is on a queue */
1623 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1624 		sxfer->entry.tqe_prev = NULL;
1625 		libusb10_complete_transfer(NULL,
1626 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1627 		/* make sure our event loop spins the done handler */
1628 		libusb_interrupt_event_handler(dev->ctx);
1629 	} else if (pxfer0 == NULL || pxfer1 == NULL) {
1630 		/* not started */
1631 		retval = LIBUSB_ERROR_NOT_FOUND;
1632 	} else if (libusb20_tr_get_priv_sc1(pxfer0) == sxfer) {
1633 		libusb10_complete_transfer(pxfer0,
1634 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1635 		if (dev->device_is_gone != 0) {
1636 			/* clear transfer pointer */
1637 			libusb20_tr_set_priv_sc1(pxfer0, NULL);
1638 			/* make sure our event loop spins the done handler */
1639 			libusb_interrupt_event_handler(dev->ctx);
1640 		} else {
1641 			libusb20_tr_stop(pxfer0);
1642 			/* make sure the queue doesn't stall */
1643 			libusb10_submit_transfer_sub(devh, endpoint);
1644 		}
1645 	} else if (libusb20_tr_get_priv_sc1(pxfer1) == sxfer) {
1646 		libusb10_complete_transfer(pxfer1,
1647 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1648 		/* check if handle is still active */
1649 		if (dev->device_is_gone != 0) {
1650 			/* clear transfer pointer */
1651 			libusb20_tr_set_priv_sc1(pxfer1, NULL);
1652 			/* make sure our event loop spins the done handler */
1653 			libusb_interrupt_event_handler(dev->ctx);
1654 		} else {
1655 			libusb20_tr_stop(pxfer1);
1656 			/* make sure the queue doesn't stall */
1657 			libusb10_submit_transfer_sub(devh, endpoint);
1658 		}
1659 	} else {
1660 		/* not started */
1661 		retval = LIBUSB_ERROR_NOT_FOUND;
1662 	}
1663 
1664 	CTX_UNLOCK(dev->ctx);
1665 
1666 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_cancel_transfer leave");
1667 
1668 	return (retval);
1669 }
1670 
1671 UNEXPORTED void
libusb10_cancel_all_transfer(libusb_device * dev)1672 libusb10_cancel_all_transfer(libusb_device *dev)
1673 {
1674 	struct libusb20_device *pdev = dev->os_priv;
1675 	unsigned x;
1676 
1677 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1678 		struct libusb20_transfer *xfer;
1679 
1680 		xfer = libusb20_tr_get_pointer(pdev, x);
1681 		if (xfer == NULL)
1682 			continue;
1683 		libusb20_tr_close(xfer);
1684 	}
1685 }
1686 
1687 UNEXPORTED void
libusb10_cancel_all_transfer_locked(struct libusb20_device * pdev,struct libusb_device * dev)1688 libusb10_cancel_all_transfer_locked(struct libusb20_device *pdev, struct libusb_device *dev)
1689 {
1690 	struct libusb_super_transfer *sxfer;
1691 	unsigned x;
1692 
1693 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1694 		struct libusb20_transfer *xfer;
1695 
1696 		xfer = libusb20_tr_get_pointer(pdev, x);
1697 		if (xfer == NULL)
1698 			continue;
1699 		if (libusb20_tr_pending(xfer) == 0)
1700 			continue;
1701 		sxfer = libusb20_tr_get_priv_sc1(xfer);
1702 		if (sxfer == NULL)
1703 			continue;
1704 		/* complete pending transfer */
1705 		libusb10_complete_transfer(xfer, sxfer, LIBUSB_TRANSFER_ERROR);
1706 	}
1707 
1708 	while ((sxfer = TAILQ_FIRST(&dev->tr_head))) {
1709 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1710 
1711 		/* complete pending transfer */
1712 		libusb10_complete_transfer(NULL, sxfer, LIBUSB_TRANSFER_ERROR);
1713 	}
1714 }
1715 
1716 uint16_t
libusb_cpu_to_le16(uint16_t x)1717 libusb_cpu_to_le16(uint16_t x)
1718 {
1719 	return (htole16(x));
1720 }
1721 
1722 uint16_t
libusb_le16_to_cpu(uint16_t x)1723 libusb_le16_to_cpu(uint16_t x)
1724 {
1725 	return (le16toh(x));
1726 }
1727 
1728 const char *
libusb_strerror(int code)1729 libusb_strerror(int code)
1730 {
1731 	switch (code) {
1732 	case LIBUSB_SUCCESS:
1733 		return ("Success");
1734 	case LIBUSB_ERROR_IO:
1735 		return ("I/O error");
1736 	case LIBUSB_ERROR_INVALID_PARAM:
1737 		return ("Invalid parameter");
1738 	case LIBUSB_ERROR_ACCESS:
1739 		return ("Permissions error");
1740 	case LIBUSB_ERROR_NO_DEVICE:
1741 		return ("No device");
1742 	case LIBUSB_ERROR_NOT_FOUND:
1743 		return ("Not found");
1744 	case LIBUSB_ERROR_BUSY:
1745 		return ("Device busy");
1746 	case LIBUSB_ERROR_TIMEOUT:
1747 		return ("Timeout");
1748 	case LIBUSB_ERROR_OVERFLOW:
1749 		return ("Overflow");
1750 	case LIBUSB_ERROR_PIPE:
1751 		return ("Pipe error");
1752 	case LIBUSB_ERROR_INTERRUPTED:
1753 		return ("Interrupted");
1754 	case LIBUSB_ERROR_NO_MEM:
1755 		return ("Out of memory");
1756 	case LIBUSB_ERROR_NOT_SUPPORTED:
1757 		return ("Not supported");
1758 	case LIBUSB_ERROR_OTHER:
1759 		return ("Other error");
1760 	default:
1761 		return ("Unknown error");
1762 	}
1763 }
1764 
1765 const char *
libusb_error_name(int code)1766 libusb_error_name(int code)
1767 {
1768 	switch (code) {
1769 	case LIBUSB_SUCCESS:
1770 		return ("LIBUSB_SUCCESS");
1771 	case LIBUSB_ERROR_IO:
1772 		return ("LIBUSB_ERROR_IO");
1773 	case LIBUSB_ERROR_INVALID_PARAM:
1774 		return ("LIBUSB_ERROR_INVALID_PARAM");
1775 	case LIBUSB_ERROR_ACCESS:
1776 		return ("LIBUSB_ERROR_ACCESS");
1777 	case LIBUSB_ERROR_NO_DEVICE:
1778 		return ("LIBUSB_ERROR_NO_DEVICE");
1779 	case LIBUSB_ERROR_NOT_FOUND:
1780 		return ("LIBUSB_ERROR_NOT_FOUND");
1781 	case LIBUSB_ERROR_BUSY:
1782 		return ("LIBUSB_ERROR_BUSY");
1783 	case LIBUSB_ERROR_TIMEOUT:
1784 		return ("LIBUSB_ERROR_TIMEOUT");
1785 	case LIBUSB_ERROR_OVERFLOW:
1786 		return ("LIBUSB_ERROR_OVERFLOW");
1787 	case LIBUSB_ERROR_PIPE:
1788 		return ("LIBUSB_ERROR_PIPE");
1789 	case LIBUSB_ERROR_INTERRUPTED:
1790 		return ("LIBUSB_ERROR_INTERRUPTED");
1791 	case LIBUSB_ERROR_NO_MEM:
1792 		return ("LIBUSB_ERROR_NO_MEM");
1793 	case LIBUSB_ERROR_NOT_SUPPORTED:
1794 		return ("LIBUSB_ERROR_NOT_SUPPORTED");
1795 	case LIBUSB_ERROR_OTHER:
1796 		return ("LIBUSB_ERROR_OTHER");
1797 	default:
1798 		return ("LIBUSB_ERROR_UNKNOWN");
1799 	}
1800 }
1801 
1802 int
libusb_has_capability(uint32_t capability)1803 libusb_has_capability(uint32_t capability)
1804 {
1805 
1806 	switch (capability) {
1807 	case LIBUSB_CAP_HAS_CAPABILITY:
1808 	case LIBUSB_CAP_HAS_HOTPLUG:
1809 	case LIBUSB_CAP_HAS_HID_ACCESS:
1810 	case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
1811 		return (1);
1812 	default:
1813 		return (0);
1814 	}
1815 }
1816 
1817 void
libusb_log_va_args(struct libusb_context * ctx,enum libusb_log_level level,const char * fmt,...)1818 libusb_log_va_args(struct libusb_context *ctx, enum libusb_log_level level,
1819     const char *fmt, ...)
1820 {
1821 	static const char *log_prefix[5] = {
1822 		[LIBUSB_LOG_LEVEL_ERROR] = "LIBUSB_ERROR",
1823 		[LIBUSB_LOG_LEVEL_WARNING] = "LIBUSB_WARN",
1824 		[LIBUSB_LOG_LEVEL_INFO] = "LIBUSB_INFO",
1825 		[LIBUSB_LOG_LEVEL_DEBUG] = "LIBUSB_DEBUG",
1826 	};
1827 
1828 	char buffer[LIBUSB_LOG_BUFFER_SIZE];
1829 	char new_fmt[LIBUSB_LOG_BUFFER_SIZE];
1830 	va_list args;
1831 
1832 	ctx = GET_CONTEXT(ctx);
1833 
1834 	if (ctx->debug < level)
1835 		return;
1836 
1837 	va_start(args, fmt);
1838 
1839 	snprintf(new_fmt, sizeof(new_fmt), "%s: %s\n", log_prefix[level], fmt);
1840 	vsnprintf(buffer, sizeof(buffer), new_fmt, args);
1841 	fputs(buffer, stdout);
1842 
1843 	va_end(args);
1844 }
1845