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