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