xref: /freebsd/lib/libusb/libusb10.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 static void
118 libusb10_wakeup_event_loop(libusb_context *ctx)
119 {
120 	uint8_t dummy = 0;
121 	int err;
122 
123 	err = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
124 	if (err < (int)sizeof(dummy)) {
125 		/* ignore error, if any */
126 		DPRINTF(ctx, LIBUSB_DEBUG_FUNCTION, "Waking up event loop failed!");
127 	}
128 }
129 
130 int
131 libusb_init(libusb_context **context)
132 {
133 	struct libusb_context *ctx;
134 	pthread_condattr_t attr;
135 	char *debug;
136 	int ret;
137 
138 	ctx = malloc(sizeof(*ctx));
139 	if (!ctx)
140 		return (LIBUSB_ERROR_INVALID_PARAM);
141 
142 	memset(ctx, 0, sizeof(*ctx));
143 
144 	debug = getenv("LIBUSB_DEBUG");
145 	if (debug != NULL) {
146 		ctx->debug = atoi(debug);
147 		if (ctx->debug != 0)
148 			ctx->debug_fixed = 1;
149 	}
150 	TAILQ_INIT(&ctx->pollfds);
151 	TAILQ_INIT(&ctx->tr_done);
152 	TAILQ_INIT(&ctx->hotplug_cbh);
153 	TAILQ_INIT(&ctx->hotplug_devs);
154 
155 	if (pthread_mutex_init(&ctx->ctx_lock, NULL) != 0) {
156 		free(ctx);
157 		return (LIBUSB_ERROR_NO_MEM);
158 	}
159 	if (pthread_mutex_init(&ctx->hotplug_lock, NULL) != 0) {
160 		pthread_mutex_destroy(&ctx->ctx_lock);
161 		free(ctx);
162 		return (LIBUSB_ERROR_NO_MEM);
163 	}
164 	if (pthread_condattr_init(&attr) != 0) {
165 		pthread_mutex_destroy(&ctx->ctx_lock);
166 		pthread_mutex_destroy(&ctx->hotplug_lock);
167 		free(ctx);
168 		return (LIBUSB_ERROR_NO_MEM);
169 	}
170 	if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) != 0) {
171 		pthread_mutex_destroy(&ctx->ctx_lock);
172 		pthread_mutex_destroy(&ctx->hotplug_lock);
173 		pthread_condattr_destroy(&attr);
174 		free(ctx);
175 		return (LIBUSB_ERROR_OTHER);
176 	}
177 	if (pthread_cond_init(&ctx->ctx_cond, &attr) != 0) {
178 		pthread_mutex_destroy(&ctx->ctx_lock);
179 		pthread_mutex_destroy(&ctx->hotplug_lock);
180 		pthread_condattr_destroy(&attr);
181 		free(ctx);
182 		return (LIBUSB_ERROR_NO_MEM);
183 	}
184 	pthread_condattr_destroy(&attr);
185 
186 	ctx->ctx_handler = NO_THREAD;
187 	ctx->hotplug_handler = NO_THREAD;
188 
189 	ret = pipe(ctx->ctrl_pipe);
190 	if (ret < 0) {
191 		pthread_mutex_destroy(&ctx->ctx_lock);
192 		pthread_mutex_destroy(&ctx->hotplug_lock);
193 		pthread_cond_destroy(&ctx->ctx_cond);
194 		free(ctx);
195 		return (LIBUSB_ERROR_OTHER);
196 	}
197 	/* set non-blocking mode on the control pipe to avoid deadlock */
198 	libusb_set_nonblocking(ctx->ctrl_pipe[0]);
199 	libusb_set_nonblocking(ctx->ctrl_pipe[1]);
200 
201 	libusb10_add_pollfd(ctx, &ctx->ctx_poll, NULL, ctx->ctrl_pipe[0], POLLIN);
202 
203 	pthread_mutex_lock(&default_context_lock);
204 	if (usbi_default_context == NULL) {
205 		usbi_default_context = ctx;
206 	}
207 	pthread_mutex_unlock(&default_context_lock);
208 
209 	if (context)
210 		*context = ctx;
211 
212 	DPRINTF(ctx, LIBUSB_DEBUG_FUNCTION, "libusb_init complete");
213 
214 	return (0);
215 }
216 
217 void
218 libusb_exit(libusb_context *ctx)
219 {
220 	ctx = GET_CONTEXT(ctx);
221 
222 	if (ctx == NULL)
223 		return;
224 
225 	/* stop hotplug thread, if any */
226 
227 	if (ctx->hotplug_handler != NO_THREAD) {
228 		pthread_t td;
229 		void *ptr;
230 
231 		HOTPLUG_LOCK(ctx);
232 		td = ctx->hotplug_handler;
233 		ctx->hotplug_handler = NO_THREAD;
234 		HOTPLUG_UNLOCK(ctx);
235 
236 		pthread_join(td, &ptr);
237 	}
238 
239 	/* XXX cleanup devices */
240 
241 	libusb10_remove_pollfd(ctx, &ctx->ctx_poll);
242 	close(ctx->ctrl_pipe[0]);
243 	close(ctx->ctrl_pipe[1]);
244 	pthread_mutex_destroy(&ctx->ctx_lock);
245 	pthread_mutex_destroy(&ctx->hotplug_lock);
246 	pthread_cond_destroy(&ctx->ctx_cond);
247 
248 	pthread_mutex_lock(&default_context_lock);
249 	if (ctx == usbi_default_context) {
250 		usbi_default_context = NULL;
251 	}
252 	pthread_mutex_unlock(&default_context_lock);
253 
254 	free(ctx);
255 }
256 
257 /* Device handling and initialisation. */
258 
259 ssize_t
260 libusb_get_device_list(libusb_context *ctx, libusb_device ***list)
261 {
262 	struct libusb20_backend *usb_backend;
263 	struct libusb20_device *pdev;
264 	struct libusb_device *dev;
265 	int i;
266 
267 	ctx = GET_CONTEXT(ctx);
268 
269 	if (ctx == NULL)
270 		return (LIBUSB_ERROR_INVALID_PARAM);
271 
272 	if (list == NULL)
273 		return (LIBUSB_ERROR_INVALID_PARAM);
274 
275 	usb_backend = libusb20_be_alloc_default();
276 	if (usb_backend == NULL)
277 		return (LIBUSB_ERROR_NO_MEM);
278 
279 	/* figure out how many USB devices are present */
280 	pdev = NULL;
281 	i = 0;
282 	while ((pdev = libusb20_be_device_foreach(usb_backend, pdev)))
283 		i++;
284 
285 	/* allocate device pointer list */
286 	*list = malloc((i + 1) * sizeof(void *));
287 	if (*list == NULL) {
288 		libusb20_be_free(usb_backend);
289 		return (LIBUSB_ERROR_NO_MEM);
290 	}
291 	/* create libusb v1.0 compliant devices */
292 	i = 0;
293 	while ((pdev = libusb20_be_device_foreach(usb_backend, NULL))) {
294 
295 		dev = malloc(sizeof(*dev));
296 		if (dev == NULL) {
297 			while (i != 0) {
298 				libusb_unref_device((*list)[i - 1]);
299 				i--;
300 			}
301 			free(*list);
302 			*list = NULL;
303 			libusb20_be_free(usb_backend);
304 			return (LIBUSB_ERROR_NO_MEM);
305 		}
306 		/* get device into libUSB v1.0 list */
307 		libusb20_be_dequeue_device(usb_backend, pdev);
308 
309 		memset(dev, 0, sizeof(*dev));
310 
311 		/* init transfer queues */
312 		TAILQ_INIT(&dev->tr_head);
313 
314 		/* set context we belong to */
315 		dev->ctx = ctx;
316 
317 		/* link together the two structures */
318 		dev->os_priv = pdev;
319 		pdev->privLuData = dev;
320 
321 		(*list)[i] = libusb_ref_device(dev);
322 		i++;
323 	}
324 	(*list)[i] = NULL;
325 
326 	libusb20_be_free(usb_backend);
327 	return (i);
328 }
329 
330 void
331 libusb_free_device_list(libusb_device **list, int unref_devices)
332 {
333 	int i;
334 
335 	if (list == NULL)
336 		return;			/* be NULL safe */
337 
338 	if (unref_devices) {
339 		for (i = 0; list[i] != NULL; i++)
340 			libusb_unref_device(list[i]);
341 	}
342 	free(list);
343 }
344 
345 uint8_t
346 libusb_get_bus_number(libusb_device *dev)
347 {
348 	if (dev == NULL)
349 		return (0);		/* should not happen */
350 	return (libusb20_dev_get_bus_number(dev->os_priv));
351 }
352 
353 uint8_t
354 libusb_get_port_number(libusb_device *dev)
355 {
356 	if (dev == NULL)
357 		return (0);		/* should not happen */
358 	return (libusb20_dev_get_parent_port(dev->os_priv));
359 }
360 
361 int
362 libusb_get_port_numbers(libusb_device *dev, uint8_t *buf, uint8_t bufsize)
363 {
364 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
365 }
366 
367 int
368 libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t *buf,
369     uint8_t bufsize)
370 {
371 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
372 }
373 
374 uint8_t
375 libusb_get_device_address(libusb_device *dev)
376 {
377 	if (dev == NULL)
378 		return (0);		/* should not happen */
379 	return (libusb20_dev_get_address(dev->os_priv));
380 }
381 
382 enum libusb_speed
383 libusb_get_device_speed(libusb_device *dev)
384 {
385 	if (dev == NULL)
386 		return (LIBUSB_SPEED_UNKNOWN);	/* should not happen */
387 
388 	switch (libusb20_dev_get_speed(dev->os_priv)) {
389 	case LIBUSB20_SPEED_LOW:
390 		return (LIBUSB_SPEED_LOW);
391 	case LIBUSB20_SPEED_FULL:
392 		return (LIBUSB_SPEED_FULL);
393 	case LIBUSB20_SPEED_HIGH:
394 		return (LIBUSB_SPEED_HIGH);
395 	case LIBUSB20_SPEED_SUPER:
396 		return (LIBUSB_SPEED_SUPER);
397 	default:
398 		break;
399 	}
400 	return (LIBUSB_SPEED_UNKNOWN);
401 }
402 
403 int
404 libusb_get_max_packet_size(libusb_device *dev, uint8_t endpoint)
405 {
406 	struct libusb_config_descriptor *pdconf;
407 	struct libusb_interface *pinf;
408 	struct libusb_interface_descriptor *pdinf;
409 	struct libusb_endpoint_descriptor *pdend;
410 	int i;
411 	int j;
412 	int k;
413 	int ret;
414 
415 	if (dev == NULL)
416 		return (LIBUSB_ERROR_NO_DEVICE);
417 
418 	ret = libusb_get_active_config_descriptor(dev, &pdconf);
419 	if (ret < 0)
420 		return (ret);
421 
422 	ret = LIBUSB_ERROR_NOT_FOUND;
423 	for (i = 0; i < pdconf->bNumInterfaces; i++) {
424 		pinf = &pdconf->interface[i];
425 		for (j = 0; j < pinf->num_altsetting; j++) {
426 			pdinf = &pinf->altsetting[j];
427 			for (k = 0; k < pdinf->bNumEndpoints; k++) {
428 				pdend = &pdinf->endpoint[k];
429 				if (pdend->bEndpointAddress == endpoint) {
430 					ret = pdend->wMaxPacketSize;
431 					goto out;
432 				}
433 			}
434 		}
435 	}
436 
437 out:
438 	libusb_free_config_descriptor(pdconf);
439 	return (ret);
440 }
441 
442 int
443 libusb_get_max_iso_packet_size(libusb_device *dev, uint8_t endpoint)
444 {
445 	int multiplier;
446 	int ret;
447 
448 	ret = libusb_get_max_packet_size(dev, endpoint);
449 
450 	switch (libusb20_dev_get_speed(dev->os_priv)) {
451 	case LIBUSB20_SPEED_LOW:
452 	case LIBUSB20_SPEED_FULL:
453 		break;
454 	default:
455 		if (ret > -1) {
456 			multiplier = (1 + ((ret >> 11) & 3));
457 			if (multiplier > 3)
458 				multiplier = 3;
459 			ret = (ret & 0x7FF) * multiplier;
460 		}
461 		break;
462 	}
463 	return (ret);
464 }
465 
466 libusb_device *
467 libusb_ref_device(libusb_device *dev)
468 {
469 	if (dev == NULL)
470 		return (NULL);		/* be NULL safe */
471 
472 	CTX_LOCK(dev->ctx);
473 	dev->refcnt++;
474 	CTX_UNLOCK(dev->ctx);
475 
476 	return (dev);
477 }
478 
479 void
480 libusb_unref_device(libusb_device *dev)
481 {
482 	if (dev == NULL)
483 		return;			/* be NULL safe */
484 
485 	CTX_LOCK(dev->ctx);
486 	dev->refcnt--;
487 	CTX_UNLOCK(dev->ctx);
488 
489 	if (dev->refcnt == 0) {
490 		libusb20_dev_free(dev->os_priv);
491 		free(dev);
492 	}
493 }
494 
495 int
496 libusb_open(libusb_device *dev, libusb_device_handle **devh)
497 {
498 	libusb_context *ctx = dev->ctx;
499 	struct libusb20_device *pdev = dev->os_priv;
500 	int err;
501 
502 	if (devh == NULL)
503 		return (LIBUSB_ERROR_INVALID_PARAM);
504 
505 	/* set default device handle value */
506 	*devh = NULL;
507 
508 	dev = libusb_ref_device(dev);
509 	if (dev == NULL)
510 		return (LIBUSB_ERROR_INVALID_PARAM);
511 
512 	err = libusb20_dev_open(pdev, LIBUSB_NUM_SW_ENDPOINTS);
513 	if (err) {
514 		libusb_unref_device(dev);
515 		return (LIBUSB_ERROR_NO_MEM);
516 	}
517 	libusb10_add_pollfd(ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
518 	    POLLOUT | POLLRDNORM | POLLWRNORM);
519 
520 	/* make sure our event loop detects the new device */
521 	libusb10_wakeup_event_loop(ctx);
522 
523 	*devh = pdev;
524 
525 	return (0);
526 }
527 
528 libusb_device_handle *
529 libusb_open_device_with_vid_pid(libusb_context *ctx, uint16_t vendor_id,
530     uint16_t product_id)
531 {
532 	struct libusb_device **devs;
533 	struct libusb20_device *pdev;
534 	struct LIBUSB20_DEVICE_DESC_DECODED *pdesc;
535 	int i;
536 	int j;
537 
538 	ctx = GET_CONTEXT(ctx);
539 	if (ctx == NULL)
540 		return (NULL);		/* be NULL safe */
541 
542 	DPRINTF(ctx, LIBUSB_DEBUG_FUNCTION, "libusb_open_device_width_vid_pid enter");
543 
544 	if ((i = libusb_get_device_list(ctx, &devs)) < 0)
545 		return (NULL);
546 
547 	pdev = NULL;
548 	for (j = 0; j < i; j++) {
549 		struct libusb20_device *tdev;
550 
551 		tdev = devs[j]->os_priv;
552 		pdesc = libusb20_dev_get_device_desc(tdev);
553 		/*
554 		 * NOTE: The USB library will automatically swap the
555 		 * fields in the device descriptor to be of host
556 		 * endian type!
557 		 */
558 		if (pdesc->idVendor == vendor_id &&
559 		    pdesc->idProduct == product_id) {
560 			libusb_open(devs[j], &pdev);
561 			break;
562 		}
563 	}
564 
565 	libusb_free_device_list(devs, 1);
566 	DPRINTF(ctx, LIBUSB_DEBUG_FUNCTION, "libusb_open_device_width_vid_pid leave");
567 	return (pdev);
568 }
569 
570 void
571 libusb_close(struct libusb20_device *pdev)
572 {
573 	libusb_context *ctx;
574 	struct libusb_device *dev;
575 
576 	if (pdev == NULL)
577 		return;			/* be NULL safe */
578 
579 	dev = libusb_get_device(pdev);
580 	ctx = dev->ctx;
581 
582 	libusb10_remove_pollfd(ctx, &dev->dev_poll);
583 
584 	libusb20_dev_close(pdev);
585 
586 	/* unref will free the "pdev" when the refcount reaches zero */
587 	libusb_unref_device(dev);
588 
589 	/* make sure our event loop detects the closed device */
590 	libusb10_wakeup_event_loop(ctx);
591 }
592 
593 libusb_device *
594 libusb_get_device(struct libusb20_device *pdev)
595 {
596 	if (pdev == NULL)
597 		return (NULL);
598 	return ((libusb_device *)pdev->privLuData);
599 }
600 
601 int
602 libusb_get_configuration(struct libusb20_device *pdev, int *config)
603 {
604 	struct libusb20_config *pconf;
605 
606 	if (pdev == NULL || config == NULL)
607 		return (LIBUSB_ERROR_INVALID_PARAM);
608 
609 	pconf = libusb20_dev_alloc_config(pdev, libusb20_dev_get_config_index(pdev));
610 	if (pconf == NULL)
611 		return (LIBUSB_ERROR_NO_MEM);
612 
613 	*config = pconf->desc.bConfigurationValue;
614 
615 	free(pconf);
616 
617 	return (0);
618 }
619 
620 int
621 libusb_set_configuration(struct libusb20_device *pdev, int configuration)
622 {
623 	struct libusb20_config *pconf;
624 	struct libusb_device *dev;
625 	int err;
626 	uint8_t i;
627 
628 	dev = libusb_get_device(pdev);
629 	if (dev == NULL)
630 		return (LIBUSB_ERROR_INVALID_PARAM);
631 
632 	if (configuration < 1) {
633 		/* unconfigure */
634 		i = 255;
635 	} else {
636 		for (i = 0; i != 255; i++) {
637 			uint8_t found;
638 
639 			pconf = libusb20_dev_alloc_config(pdev, i);
640 			if (pconf == NULL)
641 				return (LIBUSB_ERROR_INVALID_PARAM);
642 			found = (pconf->desc.bConfigurationValue
643 			    == configuration);
644 			free(pconf);
645 
646 			if (found)
647 				goto set_config;
648 		}
649 		return (LIBUSB_ERROR_INVALID_PARAM);
650 	}
651 
652 set_config:
653 
654 	libusb10_cancel_all_transfer(dev);
655 
656 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
657 
658 	err = libusb20_dev_set_config_index(pdev, i);
659 
660 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
661 	    POLLOUT | POLLRDNORM | POLLWRNORM);
662 
663 	return (err ? LIBUSB_ERROR_INVALID_PARAM : 0);
664 }
665 
666 int
667 libusb_claim_interface(struct libusb20_device *pdev, int interface_number)
668 {
669 	libusb_device *dev;
670 	int err = 0;
671 
672 	dev = libusb_get_device(pdev);
673 	if (dev == NULL)
674 		return (LIBUSB_ERROR_INVALID_PARAM);
675 
676 	if (interface_number < 0 || interface_number > 31)
677 		return (LIBUSB_ERROR_INVALID_PARAM);
678 
679 	if (pdev->auto_detach != 0) {
680 		err = libusb_detach_kernel_driver(pdev, interface_number);
681 		if (err != 0)
682 			goto done;
683 	}
684 
685 	CTX_LOCK(dev->ctx);
686 	dev->claimed_interfaces |= (1 << interface_number);
687 	CTX_UNLOCK(dev->ctx);
688 done:
689 	return (err);
690 }
691 
692 int
693 libusb_release_interface(struct libusb20_device *pdev, int interface_number)
694 {
695 	libusb_device *dev;
696 	int err = 0;
697 
698 	dev = libusb_get_device(pdev);
699 	if (dev == NULL)
700 		return (LIBUSB_ERROR_INVALID_PARAM);
701 
702 	if (interface_number < 0 || interface_number > 31)
703 		return (LIBUSB_ERROR_INVALID_PARAM);
704 
705 	if (pdev->auto_detach != 0) {
706 		err = libusb_attach_kernel_driver(pdev, interface_number);
707 		if (err != 0)
708 			goto done;
709 	}
710 
711 	CTX_LOCK(dev->ctx);
712 	if (!(dev->claimed_interfaces & (1 << interface_number)))
713 		err = LIBUSB_ERROR_NOT_FOUND;
714 	else
715 		dev->claimed_interfaces &= ~(1 << interface_number);
716 	CTX_UNLOCK(dev->ctx);
717 done:
718 	return (err);
719 }
720 
721 int
722 libusb_set_interface_alt_setting(struct libusb20_device *pdev,
723     int interface_number, int alternate_setting)
724 {
725 	libusb_device *dev;
726 	int err = 0;
727 
728 	dev = libusb_get_device(pdev);
729 	if (dev == NULL)
730 		return (LIBUSB_ERROR_INVALID_PARAM);
731 
732 	if (interface_number < 0 || interface_number > 31)
733 		return (LIBUSB_ERROR_INVALID_PARAM);
734 
735 	CTX_LOCK(dev->ctx);
736 	if (!(dev->claimed_interfaces & (1 << interface_number)))
737 		err = LIBUSB_ERROR_NOT_FOUND;
738 	CTX_UNLOCK(dev->ctx);
739 
740 	if (err)
741 		return (err);
742 
743 	libusb10_cancel_all_transfer(dev);
744 
745 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
746 
747 	err = libusb20_dev_set_alt_index(pdev,
748 	    interface_number, alternate_setting);
749 
750 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
751 	    pdev, libusb20_dev_get_fd(pdev),
752 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
753 
754 	return (err ? LIBUSB_ERROR_OTHER : 0);
755 }
756 
757 static struct libusb20_transfer *
758 libusb10_get_transfer(struct libusb20_device *pdev,
759     uint8_t endpoint, uint8_t xfer_index)
760 {
761 	xfer_index &= 1;	/* double buffering */
762 
763 	xfer_index |= (endpoint & LIBUSB20_ENDPOINT_ADDRESS_MASK) * 4;
764 
765 	if (endpoint & LIBUSB20_ENDPOINT_DIR_MASK) {
766 		/* this is an IN endpoint */
767 		xfer_index |= 2;
768 	}
769 	return (libusb20_tr_get_pointer(pdev, xfer_index));
770 }
771 
772 int
773 libusb_clear_halt(struct libusb20_device *pdev, uint8_t endpoint)
774 {
775 	struct libusb20_transfer *xfer;
776 	struct libusb_device *dev;
777 	int err;
778 
779 	xfer = libusb10_get_transfer(pdev, endpoint, 0);
780 	if (xfer == NULL)
781 		return (LIBUSB_ERROR_INVALID_PARAM);
782 
783 	dev = libusb_get_device(pdev);
784 	if (dev == NULL)
785 		return (LIBUSB_ERROR_INVALID_PARAM);
786 
787 	CTX_LOCK(dev->ctx);
788 	err = libusb20_tr_open(xfer, 0, 1, endpoint);
789 	CTX_UNLOCK(dev->ctx);
790 
791 	if (err != 0 && err != LIBUSB20_ERROR_BUSY)
792 		return (LIBUSB_ERROR_OTHER);
793 
794 	libusb20_tr_clear_stall_sync(xfer);
795 
796 	/* check if we opened the transfer */
797 	if (err == 0) {
798 		CTX_LOCK(dev->ctx);
799 		libusb20_tr_close(xfer);
800 		CTX_UNLOCK(dev->ctx);
801 	}
802 	return (0);			/* success */
803 }
804 
805 int
806 libusb_reset_device(struct libusb20_device *pdev)
807 {
808 	libusb_device *dev;
809 	int err;
810 
811 	dev = libusb_get_device(pdev);
812 	if (dev == NULL)
813 		return (LIBUSB_ERROR_INVALID_PARAM);
814 
815 	libusb10_cancel_all_transfer(dev);
816 
817 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
818 
819 	err = libusb20_dev_reset(pdev);
820 
821 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
822 	    pdev, libusb20_dev_get_fd(pdev),
823 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
824 
825 	return (err ? LIBUSB_ERROR_OTHER : 0);
826 }
827 
828 int
829 libusb_check_connected(struct libusb20_device *pdev)
830 {
831 	libusb_device *dev;
832 	int err;
833 
834 	dev = libusb_get_device(pdev);
835 	if (dev == NULL)
836 		return (LIBUSB_ERROR_INVALID_PARAM);
837 
838 	err = libusb20_dev_check_connected(pdev);
839 
840 	return (err ? LIBUSB_ERROR_NO_DEVICE : 0);
841 }
842 
843 int
844 libusb_kernel_driver_active(struct libusb20_device *pdev, int interface)
845 {
846 	if (pdev == NULL)
847 		return (LIBUSB_ERROR_INVALID_PARAM);
848 
849 	if (libusb20_dev_kernel_driver_active(pdev, interface))
850 		return (0);		/* no kernel driver is active */
851 	else
852 		return (1);		/* kernel driver is active */
853 }
854 
855 int
856 libusb_get_driver_np(struct libusb20_device *pdev, int interface,
857     char *name, int namelen)
858 {
859 	return (libusb_get_driver(pdev, interface, name, namelen));
860 }
861 
862 int
863 libusb_get_driver(struct libusb20_device *pdev, int interface,
864     char *name, int namelen)
865 {
866 	char *ptr;
867 	int err;
868 
869 	if (pdev == NULL)
870 		return (LIBUSB_ERROR_INVALID_PARAM);
871 	if (namelen < 1)
872 		return (LIBUSB_ERROR_INVALID_PARAM);
873 	if (namelen > 255)
874 		namelen = 255;
875 
876 	err = libusb20_dev_get_iface_desc(
877 	    pdev, interface, name, namelen);
878 
879 	if (err != 0)
880 		return (LIBUSB_ERROR_OTHER);
881 
882 	/* we only want the driver name */
883 	ptr = strstr(name, ":");
884 	if (ptr != NULL)
885 		*ptr = 0;
886 
887 	return (0);
888 }
889 
890 int
891 libusb_detach_kernel_driver_np(struct libusb20_device *pdev, int interface)
892 {
893 	return (libusb_detach_kernel_driver(pdev, interface));
894 }
895 
896 int
897 libusb_detach_kernel_driver(struct libusb20_device *pdev, int interface)
898 {
899 	int err;
900 
901 	if (pdev == NULL)
902 		return (LIBUSB_ERROR_INVALID_PARAM);
903 
904 	err = libusb20_dev_detach_kernel_driver(
905 	    pdev, interface);
906 
907 	return (err ? LIBUSB_ERROR_OTHER : 0);
908 }
909 
910 int
911 libusb_attach_kernel_driver(struct libusb20_device *pdev, int interface)
912 {
913 	if (pdev == NULL)
914 		return (LIBUSB_ERROR_INVALID_PARAM);
915 	/* stub - currently not supported by libusb20 */
916 	return (0);
917 }
918 
919 int
920 libusb_set_auto_detach_kernel_driver(libusb_device_handle *dev, int enable)
921 {
922 	dev->auto_detach = (enable ? 1 : 0);
923 	return (0);
924 }
925 
926 /* Asynchronous device I/O */
927 
928 struct libusb_transfer *
929 libusb_alloc_transfer(int iso_packets)
930 {
931 	struct libusb_transfer *uxfer;
932 	struct libusb_super_transfer *sxfer;
933 	int len;
934 
935 	len = sizeof(struct libusb_transfer) +
936 	    sizeof(struct libusb_super_transfer) +
937 	    (iso_packets * sizeof(libusb_iso_packet_descriptor));
938 
939 	sxfer = malloc(len);
940 	if (sxfer == NULL)
941 		return (NULL);
942 
943 	memset(sxfer, 0, len);
944 
945 	uxfer = (struct libusb_transfer *)(
946 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
947 
948 	/* set default value */
949 	uxfer->num_iso_packets = iso_packets;
950 
951 	return (uxfer);
952 }
953 
954 void
955 libusb_free_transfer(struct libusb_transfer *uxfer)
956 {
957 	struct libusb_super_transfer *sxfer;
958 
959 	if (uxfer == NULL)
960 		return;			/* be NULL safe */
961 
962 	/* check if we should free the transfer buffer */
963 	if (uxfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
964 		free(uxfer->buffer);
965 
966 	sxfer = (struct libusb_super_transfer *)(
967 	    (uint8_t *)uxfer - sizeof(*sxfer));
968 
969 	free(sxfer);
970 }
971 
972 static uint32_t
973 libusb10_get_maxframe(struct libusb20_device *pdev, libusb_transfer *xfer)
974 {
975 	uint32_t ret;
976 
977 	switch (xfer->type) {
978 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
979 		ret = 60 | LIBUSB20_MAX_FRAME_PRE_SCALE;	/* 60ms */
980 		break;
981 	case LIBUSB_TRANSFER_TYPE_CONTROL:
982 		ret = 2;
983 		break;
984 	default:
985 		ret = 1;
986 		break;
987 	}
988 	return (ret);
989 }
990 
991 static int
992 libusb10_get_buffsize(struct libusb20_device *pdev, libusb_transfer *xfer)
993 {
994 	int ret;
995 	int usb_speed;
996 
997 	usb_speed = libusb20_dev_get_speed(pdev);
998 
999 	switch (xfer->type) {
1000 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1001 		ret = 0;		/* kernel will auto-select */
1002 		break;
1003 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1004 		ret = 1024;
1005 		break;
1006 	default:
1007 		switch (usb_speed) {
1008 		case LIBUSB20_SPEED_LOW:
1009 			ret = 256;
1010 			break;
1011 		case LIBUSB20_SPEED_FULL:
1012 			ret = 4096;
1013 			break;
1014 		case LIBUSB20_SPEED_SUPER:
1015 			ret = 65536;
1016 			break;
1017 		default:
1018 			ret = 16384;
1019 			break;
1020 		}
1021 		break;
1022 	}
1023 	return (ret);
1024 }
1025 
1026 static int
1027 libusb10_convert_error(uint8_t status)
1028 {
1029 	;				/* indent fix */
1030 
1031 	switch (status) {
1032 	case LIBUSB20_TRANSFER_START:
1033 	case LIBUSB20_TRANSFER_COMPLETED:
1034 		return (LIBUSB_TRANSFER_COMPLETED);
1035 	case LIBUSB20_TRANSFER_OVERFLOW:
1036 		return (LIBUSB_TRANSFER_OVERFLOW);
1037 	case LIBUSB20_TRANSFER_NO_DEVICE:
1038 		return (LIBUSB_TRANSFER_NO_DEVICE);
1039 	case LIBUSB20_TRANSFER_STALL:
1040 		return (LIBUSB_TRANSFER_STALL);
1041 	case LIBUSB20_TRANSFER_CANCELLED:
1042 		return (LIBUSB_TRANSFER_CANCELLED);
1043 	case LIBUSB20_TRANSFER_TIMED_OUT:
1044 		return (LIBUSB_TRANSFER_TIMED_OUT);
1045 	default:
1046 		return (LIBUSB_TRANSFER_ERROR);
1047 	}
1048 }
1049 
1050 /* This function must be called locked */
1051 
1052 static void
1053 libusb10_complete_transfer(struct libusb20_transfer *pxfer,
1054     struct libusb_super_transfer *sxfer, int status)
1055 {
1056 	struct libusb_transfer *uxfer;
1057 	struct libusb_device *dev;
1058 
1059 	uxfer = (struct libusb_transfer *)(
1060 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1061 
1062 	if (pxfer != NULL)
1063 		libusb20_tr_set_priv_sc1(pxfer, NULL);
1064 
1065 	/* set transfer status */
1066 	uxfer->status = status;
1067 
1068 	/* update super transfer state */
1069 	sxfer->state = LIBUSB_SUPER_XFER_ST_NONE;
1070 
1071 	dev = libusb_get_device(uxfer->dev_handle);
1072 
1073 	TAILQ_INSERT_TAIL(&dev->ctx->tr_done, sxfer, entry);
1074 }
1075 
1076 /* This function must be called locked */
1077 
1078 static void
1079 libusb10_isoc_proxy(struct libusb20_transfer *pxfer)
1080 {
1081 	struct libusb_super_transfer *sxfer;
1082 	struct libusb_transfer *uxfer;
1083 	uint32_t actlen;
1084 	uint16_t iso_packets;
1085 	uint16_t i;
1086 	uint8_t status;
1087 
1088 	status = libusb20_tr_get_status(pxfer);
1089 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1090 	actlen = libusb20_tr_get_actual_length(pxfer);
1091 	iso_packets = libusb20_tr_get_max_frames(pxfer);
1092 
1093 	if (sxfer == NULL)
1094 		return; /* cancelled - nothing to do */
1095 
1096 	uxfer = (struct libusb_transfer *)(
1097 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1098 
1099 	if (iso_packets > uxfer->num_iso_packets)
1100 		iso_packets = uxfer->num_iso_packets;
1101 
1102 	if (iso_packets == 0)
1103 		return; /* nothing to do */
1104 
1105 	/* make sure that the number of ISOCHRONOUS packets is valid */
1106 	uxfer->num_iso_packets = iso_packets;
1107 
1108 	switch (status) {
1109 	case LIBUSB20_TRANSFER_COMPLETED:
1110 		/* update actual length */
1111 		uxfer->actual_length = actlen;
1112 		for (i = 0; i != iso_packets; i++) {
1113 			uxfer->iso_packet_desc[i].actual_length =
1114 			    libusb20_tr_get_length(pxfer, i);
1115 		}
1116 		libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1117 		break;
1118 	case LIBUSB20_TRANSFER_START:
1119 		/* setup length(s) */
1120 		actlen = 0;
1121 		for (i = 0; i != iso_packets; i++) {
1122 			libusb20_tr_setup_isoc(pxfer,
1123 			    &uxfer->buffer[actlen],
1124 			    uxfer->iso_packet_desc[i].length, i);
1125 			actlen += uxfer->iso_packet_desc[i].length;
1126 		}
1127 
1128 		/* no remainder */
1129 		sxfer->rem_len = 0;
1130 
1131 		libusb20_tr_set_total_frames(pxfer, iso_packets);
1132 		libusb20_tr_submit(pxfer);
1133 
1134 		/* fork another USB transfer, if any */
1135 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1136 		break;
1137 	default:
1138 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1139 		break;
1140 	}
1141 }
1142 
1143 /* This function must be called locked */
1144 
1145 static void
1146 libusb10_bulk_intr_proxy(struct libusb20_transfer *pxfer)
1147 {
1148 	struct libusb_super_transfer *sxfer;
1149 	struct libusb_transfer *uxfer;
1150 	uint32_t max_bulk;
1151 	uint32_t actlen;
1152 	uint8_t status;
1153 	uint8_t flags;
1154 
1155 	status = libusb20_tr_get_status(pxfer);
1156 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1157 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1158 	actlen = libusb20_tr_get_actual_length(pxfer);
1159 
1160 	if (sxfer == NULL)
1161 		return;			/* cancelled - nothing to do */
1162 
1163 	uxfer = (struct libusb_transfer *)(
1164 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1165 
1166 	flags = uxfer->flags;
1167 
1168 	switch (status) {
1169 	case LIBUSB20_TRANSFER_COMPLETED:
1170 
1171 		uxfer->actual_length += actlen;
1172 
1173 		/* check for short packet */
1174 		if (sxfer->last_len != actlen) {
1175 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1176 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1177 			} else {
1178 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1179 			}
1180 			break;
1181 		}
1182 		/* check for end of data */
1183 		if (sxfer->rem_len == 0) {
1184 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1185 			break;
1186 		}
1187 		/* FALLTHROUGH */
1188 
1189 	case LIBUSB20_TRANSFER_START:
1190 		if (max_bulk > sxfer->rem_len) {
1191 			max_bulk = sxfer->rem_len;
1192 		}
1193 		/* setup new BULK or INTERRUPT transaction */
1194 		libusb20_tr_setup_bulk(pxfer,
1195 		    sxfer->curr_data, max_bulk, uxfer->timeout);
1196 
1197 		/* update counters */
1198 		sxfer->last_len = max_bulk;
1199 		sxfer->curr_data += max_bulk;
1200 		sxfer->rem_len -= max_bulk;
1201 
1202 		libusb20_tr_submit(pxfer);
1203 
1204 		/* check if we can fork another USB transfer */
1205 		if (sxfer->rem_len == 0)
1206 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1207 		break;
1208 
1209 	default:
1210 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1211 		break;
1212 	}
1213 }
1214 
1215 /* This function must be called locked */
1216 
1217 static void
1218 libusb10_ctrl_proxy(struct libusb20_transfer *pxfer)
1219 {
1220 	struct libusb_super_transfer *sxfer;
1221 	struct libusb_transfer *uxfer;
1222 	uint32_t max_bulk;
1223 	uint32_t actlen;
1224 	uint8_t status;
1225 	uint8_t flags;
1226 
1227 	status = libusb20_tr_get_status(pxfer);
1228 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1229 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1230 	actlen = libusb20_tr_get_actual_length(pxfer);
1231 
1232 	if (sxfer == NULL)
1233 		return;			/* cancelled - nothing to do */
1234 
1235 	uxfer = (struct libusb_transfer *)(
1236 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1237 
1238 	flags = uxfer->flags;
1239 
1240 	switch (status) {
1241 	case LIBUSB20_TRANSFER_COMPLETED:
1242 
1243 		uxfer->actual_length += actlen;
1244 
1245 		/* subtract length of SETUP packet, if any */
1246 		actlen -= libusb20_tr_get_length(pxfer, 0);
1247 
1248 		/* check for short packet */
1249 		if (sxfer->last_len != actlen) {
1250 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1251 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1252 			} else {
1253 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1254 			}
1255 			break;
1256 		}
1257 		/* check for end of data */
1258 		if (sxfer->rem_len == 0) {
1259 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1260 			break;
1261 		}
1262 		/* FALLTHROUGH */
1263 
1264 	case LIBUSB20_TRANSFER_START:
1265 		if (max_bulk > sxfer->rem_len) {
1266 			max_bulk = sxfer->rem_len;
1267 		}
1268 		/* setup new CONTROL transaction */
1269 		if (status == LIBUSB20_TRANSFER_COMPLETED) {
1270 			/* next fragment - don't send SETUP packet */
1271 			libusb20_tr_set_length(pxfer, 0, 0);
1272 		} else {
1273 			/* first fragment - send SETUP packet */
1274 			libusb20_tr_set_length(pxfer, 8, 0);
1275 			libusb20_tr_set_buffer(pxfer, uxfer->buffer, 0);
1276 		}
1277 
1278 		if (max_bulk != 0) {
1279 			libusb20_tr_set_length(pxfer, max_bulk, 1);
1280 			libusb20_tr_set_buffer(pxfer, sxfer->curr_data, 1);
1281 			libusb20_tr_set_total_frames(pxfer, 2);
1282 		} else {
1283 			libusb20_tr_set_total_frames(pxfer, 1);
1284 		}
1285 
1286 		/* update counters */
1287 		sxfer->last_len = max_bulk;
1288 		sxfer->curr_data += max_bulk;
1289 		sxfer->rem_len -= max_bulk;
1290 
1291 		libusb20_tr_submit(pxfer);
1292 
1293 		/* check if we can fork another USB transfer */
1294 		if (sxfer->rem_len == 0)
1295 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1296 		break;
1297 
1298 	default:
1299 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1300 		break;
1301 	}
1302 }
1303 
1304 /* The following function must be called locked */
1305 
1306 static void
1307 libusb10_submit_transfer_sub(struct libusb20_device *pdev, uint8_t endpoint)
1308 {
1309 	struct libusb20_transfer *pxfer0;
1310 	struct libusb20_transfer *pxfer1;
1311 	struct libusb_super_transfer *sxfer;
1312 	struct libusb_transfer *uxfer;
1313 	struct libusb_device *dev;
1314 	int err;
1315 	int buffsize;
1316 	int maxframe;
1317 	int temp;
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 	/* make sure our event loop spins the done handler */
1419 	libusb10_wakeup_event_loop(dev->ctx);
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 if (dev->device_is_gone != 0) {
1461 		err = LIBUSB_ERROR_NO_DEVICE;
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 	struct libusb_device_handle *devh;
1494 	uint8_t endpoint;
1495 	int retval;
1496 
1497 	if (uxfer == NULL)
1498 		return (LIBUSB_ERROR_INVALID_PARAM);
1499 
1500 	/* check if not initialised */
1501 	if ((devh = uxfer->dev_handle) == NULL)
1502 		return (LIBUSB_ERROR_NOT_FOUND);
1503 
1504 	endpoint = uxfer->endpoint;
1505 
1506 	dev = libusb_get_device(devh);
1507 
1508 	DPRINTF(dev->ctx, LIBUSB_DEBUG_FUNCTION, "libusb_cancel_transfer enter");
1509 
1510 	sxfer = (struct libusb_super_transfer *)(
1511 	    (uint8_t *)uxfer - sizeof(*sxfer));
1512 
1513 	retval = 0;
1514 
1515 	CTX_LOCK(dev->ctx);
1516 
1517 	pxfer0 = libusb10_get_transfer(devh, endpoint, 0);
1518 	pxfer1 = libusb10_get_transfer(devh, endpoint, 1);
1519 
1520 	if (sxfer->state != LIBUSB_SUPER_XFER_ST_PEND) {
1521 		/* only update the transfer status */
1522 		uxfer->status = LIBUSB_TRANSFER_CANCELLED;
1523 		retval = LIBUSB_ERROR_NOT_FOUND;
1524 	} else if (sxfer->entry.tqe_prev != NULL) {
1525 		/* we are lucky - transfer is on a queue */
1526 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1527 		sxfer->entry.tqe_prev = NULL;
1528 		libusb10_complete_transfer(NULL,
1529 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1530 		/* make sure our event loop spins the done handler */
1531 		libusb10_wakeup_event_loop(dev->ctx);
1532 	} else if (pxfer0 == NULL || pxfer1 == NULL) {
1533 		/* not started */
1534 		retval = LIBUSB_ERROR_NOT_FOUND;
1535 	} else if (libusb20_tr_get_priv_sc1(pxfer0) == sxfer) {
1536 		libusb10_complete_transfer(pxfer0,
1537 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1538 		if (dev->device_is_gone != 0) {
1539 			/* clear transfer pointer */
1540 			libusb20_tr_set_priv_sc1(pxfer0, NULL);
1541 			/* make sure our event loop spins the done handler */
1542 			libusb10_wakeup_event_loop(dev->ctx);
1543 		} else {
1544 			libusb20_tr_stop(pxfer0);
1545 			/* make sure the queue doesn't stall */
1546 			libusb10_submit_transfer_sub(devh, endpoint);
1547 		}
1548 	} else if (libusb20_tr_get_priv_sc1(pxfer1) == sxfer) {
1549 		libusb10_complete_transfer(pxfer1,
1550 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1551 		/* check if handle is still active */
1552 		if (dev->device_is_gone != 0) {
1553 			/* clear transfer pointer */
1554 			libusb20_tr_set_priv_sc1(pxfer1, NULL);
1555 			/* make sure our event loop spins the done handler */
1556 			libusb10_wakeup_event_loop(dev->ctx);
1557 		} else {
1558 			libusb20_tr_stop(pxfer1);
1559 			/* make sure the queue doesn't stall */
1560 			libusb10_submit_transfer_sub(devh, endpoint);
1561 		}
1562 	} else {
1563 		/* not started */
1564 		retval = LIBUSB_ERROR_NOT_FOUND;
1565 	}
1566 
1567 	CTX_UNLOCK(dev->ctx);
1568 
1569 	DPRINTF(dev->ctx, LIBUSB_DEBUG_FUNCTION, "libusb_cancel_transfer leave");
1570 
1571 	return (retval);
1572 }
1573 
1574 UNEXPORTED void
1575 libusb10_cancel_all_transfer(libusb_device *dev)
1576 {
1577 	struct libusb20_device *pdev = dev->os_priv;
1578 	unsigned x;
1579 
1580 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1581 		struct libusb20_transfer *xfer;
1582 
1583 		xfer = libusb20_tr_get_pointer(pdev, x);
1584 		if (xfer == NULL)
1585 			continue;
1586 		libusb20_tr_close(xfer);
1587 	}
1588 }
1589 
1590 UNEXPORTED void
1591 libusb10_cancel_all_transfer_locked(struct libusb20_device *pdev, struct libusb_device *dev)
1592 {
1593 	struct libusb_super_transfer *sxfer;
1594 	unsigned x;
1595 
1596 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1597 		struct libusb20_transfer *xfer;
1598 
1599 		xfer = libusb20_tr_get_pointer(pdev, x);
1600 		if (xfer == NULL)
1601 			continue;
1602 		if (libusb20_tr_pending(xfer) == 0)
1603 			continue;
1604 		sxfer = libusb20_tr_get_priv_sc1(xfer);
1605 		if (sxfer == NULL)
1606 			continue;
1607 		/* complete pending transfer */
1608 		libusb10_complete_transfer(xfer, sxfer, LIBUSB_TRANSFER_ERROR);
1609 	}
1610 
1611 	while ((sxfer = TAILQ_FIRST(&dev->tr_head))) {
1612 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1613 
1614 		/* complete pending transfer */
1615 		libusb10_complete_transfer(NULL, sxfer, LIBUSB_TRANSFER_ERROR);
1616 	}
1617 }
1618 
1619 uint16_t
1620 libusb_cpu_to_le16(uint16_t x)
1621 {
1622 	return (htole16(x));
1623 }
1624 
1625 uint16_t
1626 libusb_le16_to_cpu(uint16_t x)
1627 {
1628 	return (le16toh(x));
1629 }
1630 
1631 const char *
1632 libusb_strerror(int code)
1633 {
1634 	switch (code) {
1635 	case LIBUSB_SUCCESS:
1636 		return ("Success");
1637 	case LIBUSB_ERROR_IO:
1638 		return ("I/O error");
1639 	case LIBUSB_ERROR_INVALID_PARAM:
1640 		return ("Invalid parameter");
1641 	case LIBUSB_ERROR_ACCESS:
1642 		return ("Permissions error");
1643 	case LIBUSB_ERROR_NO_DEVICE:
1644 		return ("No device");
1645 	case LIBUSB_ERROR_NOT_FOUND:
1646 		return ("Not found");
1647 	case LIBUSB_ERROR_BUSY:
1648 		return ("Device busy");
1649 	case LIBUSB_ERROR_TIMEOUT:
1650 		return ("Timeout");
1651 	case LIBUSB_ERROR_OVERFLOW:
1652 		return ("Overflow");
1653 	case LIBUSB_ERROR_PIPE:
1654 		return ("Pipe error");
1655 	case LIBUSB_ERROR_INTERRUPTED:
1656 		return ("Interrupted");
1657 	case LIBUSB_ERROR_NO_MEM:
1658 		return ("Out of memory");
1659 	case LIBUSB_ERROR_NOT_SUPPORTED:
1660 		return ("Not supported");
1661 	case LIBUSB_ERROR_OTHER:
1662 		return ("Other error");
1663 	default:
1664 		return ("Unknown error");
1665 	}
1666 }
1667 
1668 const char *
1669 libusb_error_name(int code)
1670 {
1671 	switch (code) {
1672 	case LIBUSB_SUCCESS:
1673 		return ("LIBUSB_SUCCESS");
1674 	case LIBUSB_ERROR_IO:
1675 		return ("LIBUSB_ERROR_IO");
1676 	case LIBUSB_ERROR_INVALID_PARAM:
1677 		return ("LIBUSB_ERROR_INVALID_PARAM");
1678 	case LIBUSB_ERROR_ACCESS:
1679 		return ("LIBUSB_ERROR_ACCESS");
1680 	case LIBUSB_ERROR_NO_DEVICE:
1681 		return ("LIBUSB_ERROR_NO_DEVICE");
1682 	case LIBUSB_ERROR_NOT_FOUND:
1683 		return ("LIBUSB_ERROR_NOT_FOUND");
1684 	case LIBUSB_ERROR_BUSY:
1685 		return ("LIBUSB_ERROR_BUSY");
1686 	case LIBUSB_ERROR_TIMEOUT:
1687 		return ("LIBUSB_ERROR_TIMEOUT");
1688 	case LIBUSB_ERROR_OVERFLOW:
1689 		return ("LIBUSB_ERROR_OVERFLOW");
1690 	case LIBUSB_ERROR_PIPE:
1691 		return ("LIBUSB_ERROR_PIPE");
1692 	case LIBUSB_ERROR_INTERRUPTED:
1693 		return ("LIBUSB_ERROR_INTERRUPTED");
1694 	case LIBUSB_ERROR_NO_MEM:
1695 		return ("LIBUSB_ERROR_NO_MEM");
1696 	case LIBUSB_ERROR_NOT_SUPPORTED:
1697 		return ("LIBUSB_ERROR_NOT_SUPPORTED");
1698 	case LIBUSB_ERROR_OTHER:
1699 		return ("LIBUSB_ERROR_OTHER");
1700 	default:
1701 		return ("LIBUSB_ERROR_UNKNOWN");
1702 	}
1703 }
1704