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