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