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