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