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