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