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