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