xref: /freebsd/lib/libusb/libusb10.c (revision 08dca5971b08b65f227883502d9bb9f59eebd578)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009 Sylvestre Gallon. All rights reserved.
5  * Copyright (c) 2009-2023 Hans Petter Selasky
6  * Copyright (c) 2024 Aymeric Wibo
7  * Copyright (c) 2025 ShengYi Hung
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #ifdef LIBUSB_GLOBAL_INCLUDE_FILE
32 #include LIBUSB_GLOBAL_INCLUDE_FILE
33 #else
34 #include <assert.h>
35 #include <ctype.h>
36 #include <errno.h>
37 #include <poll.h>
38 #include <pthread.h>
39 #include <signal.h>
40 #include <stdbool.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <time.h>
47 #include <sys/eventfd.h>
48 #include <sys/fcntl.h>
49 #include <sys/ioctl.h>
50 #include <sys/queue.h>
51 #include <sys/endian.h>
52 #endif
53 
54 #define	libusb_device_handle libusb20_device
55 #define	LIBUSB_LOG_BUFFER_SIZE 1024
56 
57 #include "libusb20.h"
58 #include "libusb20_desc.h"
59 #include "libusb20_int.h"
60 #include "libusb.h"
61 #include "libusb10.h"
62 
63 #define	LIBUSB_NUM_SW_ENDPOINTS	(16 * 4)
64 
65 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
66 struct libusb_context *usbi_default_context = NULL;
67 
68 /* Prototypes */
69 
70 static struct libusb20_transfer *libusb10_get_transfer(struct libusb20_device *, uint8_t, uint8_t);
71 static int libusb10_get_buffsize(struct libusb20_device *, libusb_transfer *);
72 static int libusb10_convert_error(uint8_t status);
73 static void libusb10_complete_transfer(struct libusb20_transfer *, struct libusb_super_transfer *, int);
74 static void libusb10_isoc_proxy(struct libusb20_transfer *);
75 static void libusb10_bulk_intr_proxy(struct libusb20_transfer *);
76 static void libusb10_ctrl_proxy(struct libusb20_transfer *);
77 static void libusb10_submit_transfer_sub(struct libusb20_device *, uint8_t);
78 
79 /*  Library initialisation / deinitialisation */
80 
81 static const struct libusb_version libusb_version = {
82 	.major = 1,
83 	.minor = 0,
84 	.micro = 0,
85 	.nano = 2016,
86 	.rc = "",
87 	.describe = "https://www.freebsd.org"
88 };
89 
90 static const struct libusb_language_context libusb_language_ctx[] = {
91 	{
92 	    .lang_name = "en",
93 	    .err_strs = {
94 			[-LIBUSB_SUCCESS] = "Success",
95 			[-LIBUSB_ERROR_IO] = "I/O error",
96 			[-LIBUSB_ERROR_INVALID_PARAM] = "Invalid parameter",
97 			[-LIBUSB_ERROR_ACCESS] = "Permissions error",
98 			[-LIBUSB_ERROR_NO_DEVICE] = "No device",
99 			[-LIBUSB_ERROR_NOT_FOUND] = "Not found",
100 			[-LIBUSB_ERROR_BUSY] = "Device busy",
101 			[-LIBUSB_ERROR_TIMEOUT] = "Timeout",
102 			[-LIBUSB_ERROR_OVERFLOW] = "Overflow",
103 			[-LIBUSB_ERROR_PIPE] = "Pipe error",
104 			[-LIBUSB_ERROR_INTERRUPTED] = "Interrupted",
105 			[-LIBUSB_ERROR_NO_MEM] = "Out of memory",
106 			[-LIBUSB_ERROR_NOT_SUPPORTED]  ="Not supported",
107 			[LIBUSB_ERROR_COUNT - 1] = "Other error",
108 			[LIBUSB_ERROR_COUNT] = "Unknown error",
109 		}
110 	},
111 	{
112 		.lang_name = "zh",
113 		.err_strs = {
114 			[-LIBUSB_SUCCESS] = "成功",
115 			[-LIBUSB_ERROR_IO] = "I/O 錯誤",
116 			[-LIBUSB_ERROR_INVALID_PARAM] = "不合法的參數",
117 			[-LIBUSB_ERROR_ACCESS] = "權限錯誤",
118 			[-LIBUSB_ERROR_NO_DEVICE] = "裝置不存在",
119 			[-LIBUSB_ERROR_NOT_FOUND] = "不存在",
120 			[-LIBUSB_ERROR_BUSY] = "裝置忙碌中",
121 			[-LIBUSB_ERROR_TIMEOUT] = "逾時",
122 			[-LIBUSB_ERROR_OVERFLOW] = "溢位",
123 			[-LIBUSB_ERROR_PIPE] = "管道錯誤",
124 			[-LIBUSB_ERROR_INTERRUPTED] = "被中斷",
125 			[-LIBUSB_ERROR_NO_MEM] = "記憶體不足",
126 			[-LIBUSB_ERROR_NOT_SUPPORTED]  ="不支援",
127 			[LIBUSB_ERROR_COUNT - 1] = "其他錯誤",
128 			[LIBUSB_ERROR_COUNT] = "未知錯誤",
129 		}
130 	},
131 };
132 
133 static const struct libusb_language_context *default_language_context =
134     &libusb_language_ctx[0];
135 
136 const struct libusb_version *
137 libusb_get_version(void)
138 {
139 
140 	return (&libusb_version);
141 }
142 
143 void
144 libusb_set_debug(libusb_context *ctx, int level)
145 {
146 	ctx = GET_CONTEXT(ctx);
147 	/* debug_fixed is set when the environment overrides libusb_set_debug */
148 	if (ctx && ctx->debug_fixed == 0)
149 		ctx->debug = level;
150 }
151 
152 static void
153 libusb_set_nonblocking(int f)
154 {
155 	int flags;
156 
157 	/*
158 	 * We ignore any failures in this function, hence the
159 	 * non-blocking flag is not critical to the operation of
160 	 * libUSB. We use F_GETFL and F_SETFL to be compatible with
161 	 * Linux.
162 	 */
163 
164 	flags = fcntl(f, F_GETFL, NULL);
165 	if (flags == -1)
166 		return;
167 	flags |= O_NONBLOCK;
168 	fcntl(f, F_SETFL, flags);
169 }
170 
171 void
172 libusb_interrupt_event_handler(libusb_context *ctx)
173 {
174 	int err;
175 
176 	if (ctx == NULL)
177 		return;
178 
179 	err = eventfd_write(ctx->event, 1);
180 	if (err < 0) {
181 		/* ignore error, if any */
182 		DPRINTF(ctx, LIBUSB_LOG_LEVEL_ERROR, "Waking up event loop failed!");
183 	}
184 }
185 
186 int
187 libusb_init(libusb_context **context)
188 {
189 	return (libusb_init_context(context, NULL, 0));
190 }
191 
192 int
193 libusb_init_context(libusb_context **context,
194     const struct libusb_init_option option[], int num_options)
195 {
196 	struct libusb_context *ctx;
197 	pthread_condattr_t attr;
198 	char *debug, *ep;
199 
200 	if (num_options < 0)
201 		return (LIBUSB_ERROR_INVALID_PARAM);
202 
203 	ctx = malloc(sizeof(*ctx));
204 	if (!ctx)
205 		return (LIBUSB_ERROR_INVALID_PARAM);
206 
207 	memset(ctx, 0, sizeof(*ctx));
208 	ctx->devd_pipe = -1;
209 
210 	debug = getenv("LIBUSB_DEBUG");
211 	ctx->log_cb = NULL;
212 	ctx->no_discovery = false;
213 	ctx->debug = LIBUSB_LOG_LEVEL_NONE;
214 
215 	if (debug != NULL) {
216 		/*
217 		 * If LIBUSB_DEBUG is set, we'll honor that first and
218 		 * use it to override any future libusb_set_debug()
219 		 * calls or init options.
220 		 */
221 		errno = 0;
222 		ctx->debug = strtol(debug, &ep, 10);
223 		if (errno == 0 && *ep == '\0') {
224 			ctx->debug_fixed = 1;
225 		} else {
226 			/*
227 			 * LIBUSB_DEBUG conversion failed for some reason, but
228 			 * we don't care about the specifics all that much.  We
229 			 * can't use it either way.  Force it to the default,
230 			 * 0, in case we had a partial number.
231 			 */
232 			ctx->debug = 0;
233 		}
234 	}
235 
236 	/*
237 	 * Set the default from default context then override by options
238 	 */
239 	if (usbi_default_context) {
240 		CTX_LOCK(usbi_default_context);
241 		if (usbi_default_context->no_discovery)
242 			libusb_set_option(ctx,
243 			    LIBUSB_OPTION_NO_DEVICE_DISCOVERY);
244 		/* libusb_set_option will check if debug is fixed by the
245 		   environment variable. If it is fixed, the override will not
246 		   take effect */
247 		libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL,
248 		    usbi_default_context->debug);
249 		libusb_set_option(ctx, LIBUSB_OPTION_LOG_CB,
250 		    usbi_default_context->log_cb);
251 		CTX_UNLOCK(usbi_default_context);
252 	}
253 
254 	for (int i = 0; i < num_options; i++)
255 		libusb_set_option(ctx, option[i].option, option[i].value);
256 
257 	TAILQ_INIT(&ctx->pollfds);
258 	TAILQ_INIT(&ctx->tr_done);
259 	TAILQ_INIT(&ctx->hotplug_cbh);
260 	TAILQ_INIT(&ctx->hotplug_devs);
261 
262 	if (pthread_mutex_init(&ctx->ctx_lock, NULL) != 0) {
263 		free(ctx);
264 		return (LIBUSB_ERROR_NO_MEM);
265 	}
266 	if (pthread_mutex_init(&ctx->hotplug_lock, NULL) != 0) {
267 		pthread_mutex_destroy(&ctx->ctx_lock);
268 		free(ctx);
269 		return (LIBUSB_ERROR_NO_MEM);
270 	}
271 	if (pthread_condattr_init(&attr) != 0) {
272 		pthread_mutex_destroy(&ctx->ctx_lock);
273 		pthread_mutex_destroy(&ctx->hotplug_lock);
274 		free(ctx);
275 		return (LIBUSB_ERROR_NO_MEM);
276 	}
277 	if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) != 0) {
278 		pthread_mutex_destroy(&ctx->ctx_lock);
279 		pthread_mutex_destroy(&ctx->hotplug_lock);
280 		pthread_condattr_destroy(&attr);
281 		free(ctx);
282 		return (LIBUSB_ERROR_OTHER);
283 	}
284 	if (pthread_cond_init(&ctx->ctx_cond, &attr) != 0) {
285 		pthread_mutex_destroy(&ctx->ctx_lock);
286 		pthread_mutex_destroy(&ctx->hotplug_lock);
287 		pthread_condattr_destroy(&attr);
288 		free(ctx);
289 		return (LIBUSB_ERROR_NO_MEM);
290 	}
291 	pthread_condattr_destroy(&attr);
292 
293 	ctx->ctx_handler = NO_THREAD;
294 	ctx->hotplug_handler = NO_THREAD;
295 
296 	ctx->event = eventfd(0, EFD_NONBLOCK);
297 	if (ctx->event < 0) {
298 		pthread_mutex_destroy(&ctx->ctx_lock);
299 		pthread_mutex_destroy(&ctx->hotplug_lock);
300 		pthread_cond_destroy(&ctx->ctx_cond);
301 		free(ctx);
302 		return (LIBUSB_ERROR_OTHER);
303 	}
304 
305 	libusb10_add_pollfd(ctx, &ctx->ctx_poll, NULL, ctx->event, POLLIN);
306 
307 	pthread_mutex_lock(&default_context_lock);
308 	if (usbi_default_context == NULL) {
309 		usbi_default_context = ctx;
310 	}
311 	pthread_mutex_unlock(&default_context_lock);
312 
313 	if (context)
314 		*context = ctx;
315 
316 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_INFO, "libusb_init complete");
317 
318 	signal(SIGPIPE, SIG_IGN);
319 
320 	return (0);
321 }
322 
323 void
324 libusb_exit(libusb_context *ctx)
325 {
326 	ctx = GET_CONTEXT(ctx);
327 
328 	if (ctx == NULL)
329 		return;
330 
331 	/* stop hotplug thread, if any */
332 
333 	if (ctx->hotplug_handler != NO_THREAD) {
334 		pthread_t td;
335 		void *ptr;
336 
337 		HOTPLUG_LOCK(ctx);
338 		td = ctx->hotplug_handler;
339 		ctx->hotplug_handler = NO_THREAD;
340 		if (ctx->usb_event_mode == usb_event_devd) {
341 			close(ctx->devd_pipe);
342 			ctx->devd_pipe = -1;
343 		} else if (ctx->usb_event_mode == usb_event_netlink) {
344 			close(ctx->ss.fd);
345 			ctx->ss.fd = -1;
346 		}
347 		HOTPLUG_UNLOCK(ctx);
348 
349 		pthread_join(td, &ptr);
350 	}
351 
352 	/* XXX cleanup devices */
353 
354 	libusb10_remove_pollfd(ctx, &ctx->ctx_poll);
355 	close(ctx->event);
356 	pthread_mutex_destroy(&ctx->ctx_lock);
357 	pthread_mutex_destroy(&ctx->hotplug_lock);
358 	pthread_cond_destroy(&ctx->ctx_cond);
359 
360 	pthread_mutex_lock(&default_context_lock);
361 	if (ctx == usbi_default_context) {
362 		usbi_default_context = NULL;
363 	}
364 	pthread_mutex_unlock(&default_context_lock);
365 
366 	free(ctx);
367 }
368 
369 /* Device handling and initialisation. */
370 
371 ssize_t
372 libusb_get_device_list(libusb_context *ctx, libusb_device ***list)
373 {
374 	struct libusb20_backend *usb_backend;
375 	struct libusb20_device *pdev, *parent_dev;
376 	struct libusb_device *dev;
377 	int i, j, k;
378 
379 	ctx = GET_CONTEXT(ctx);
380 
381 	if (ctx == NULL)
382 		return (LIBUSB_ERROR_INVALID_PARAM);
383 
384 	if (list == NULL)
385 		return (LIBUSB_ERROR_INVALID_PARAM);
386 
387 	usb_backend = libusb20_be_alloc_default();
388 	if (usb_backend == NULL)
389 		return (LIBUSB_ERROR_NO_MEM);
390 
391 	/* figure out how many USB devices are present */
392 	pdev = NULL;
393 	i = 0;
394 	while ((pdev = libusb20_be_device_foreach(usb_backend, pdev)))
395 		i++;
396 
397 	/* allocate device pointer list */
398 	*list = malloc((i + 1) * sizeof(void *));
399 	if (*list == NULL) {
400 		libusb20_be_free(usb_backend);
401 		return (LIBUSB_ERROR_NO_MEM);
402 	}
403 	/* create libusb v1.0 compliant devices */
404 	i = 0;
405 	while ((pdev = libusb20_be_device_foreach(usb_backend, NULL))) {
406 
407 		dev = malloc(sizeof(*dev));
408 		if (dev == NULL) {
409 			while (i != 0) {
410 				libusb_unref_device((*list)[i - 1]);
411 				i--;
412 			}
413 			free(*list);
414 			*list = NULL;
415 			libusb20_be_free(usb_backend);
416 			return (LIBUSB_ERROR_NO_MEM);
417 		}
418 		/* get device into libUSB v1.0 list */
419 		libusb20_be_dequeue_device(usb_backend, pdev);
420 
421 		memset(dev, 0, sizeof(*dev));
422 
423 		/* init transfer queues */
424 		TAILQ_INIT(&dev->tr_head);
425 
426 		/* set context we belong to */
427 		dev->ctx = ctx;
428 
429 		/* assume we have no parent by default */
430 		dev->parent_dev = NULL;
431 
432 		/* link together the two structures */
433 		dev->os_priv = pdev;
434 		pdev->privLuData = dev;
435 
436 		(*list)[i] = libusb_ref_device(dev);
437 		i++;
438 	}
439 	(*list)[i] = NULL;
440 
441 	/* for each device, find its parent */
442 	for (j = 0; j < i; j++) {
443 		pdev = (*list)[j]->os_priv;
444 
445 		for (k = 0; k < i; k++) {
446 			if (k == j)
447 				continue;
448 
449 			parent_dev = (*list)[k]->os_priv;
450 
451 			if (parent_dev->bus_number != pdev->bus_number)
452 				continue;
453 			if (parent_dev->device_address == pdev->parent_address) {
454 				(*list)[j]->parent_dev = libusb_ref_device((*list)[k]);
455 				break;
456 			}
457 		}
458 	}
459 
460 	libusb20_be_free(usb_backend);
461 	return (i);
462 }
463 
464 void
465 libusb_free_device_list(libusb_device **list, int unref_devices)
466 {
467 	int i;
468 
469 	if (list == NULL)
470 		return;			/* be NULL safe */
471 
472 	if (unref_devices) {
473 		for (i = 0; list[i] != NULL; i++)
474 			libusb_unref_device(list[i]);
475 	}
476 	free(list);
477 }
478 
479 uint8_t
480 libusb_get_bus_number(libusb_device *dev)
481 {
482 	if (dev == NULL)
483 		return (0);		/* should not happen */
484 	return (libusb20_dev_get_bus_number(dev->os_priv));
485 }
486 
487 uint8_t
488 libusb_get_port_number(libusb_device *dev)
489 {
490 	if (dev == NULL)
491 		return (0);		/* should not happen */
492 	return (libusb20_dev_get_parent_port(dev->os_priv));
493 }
494 
495 int
496 libusb_get_port_numbers(libusb_device *dev, uint8_t *buf, uint8_t bufsize)
497 {
498 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
499 }
500 
501 int
502 libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t *buf,
503     uint8_t bufsize)
504 {
505 	return (libusb20_dev_get_port_path(dev->os_priv, buf, bufsize));
506 }
507 
508 uint8_t
509 libusb_get_device_address(libusb_device *dev)
510 {
511 	if (dev == NULL)
512 		return (0);		/* should not happen */
513 	return (libusb20_dev_get_address(dev->os_priv));
514 }
515 
516 enum libusb_speed
517 libusb_get_device_speed(libusb_device *dev)
518 {
519 	if (dev == NULL)
520 		return (LIBUSB_SPEED_UNKNOWN);	/* should not happen */
521 
522 	switch (libusb20_dev_get_speed(dev->os_priv)) {
523 	case LIBUSB20_SPEED_LOW:
524 		return (LIBUSB_SPEED_LOW);
525 	case LIBUSB20_SPEED_FULL:
526 		return (LIBUSB_SPEED_FULL);
527 	case LIBUSB20_SPEED_HIGH:
528 		return (LIBUSB_SPEED_HIGH);
529 	case LIBUSB20_SPEED_SUPER:
530 		return (LIBUSB_SPEED_SUPER);
531 	case LIBUSB20_SPEED_SUPER_PLUS:
532 		return (LIBUSB_SPEED_SUPER_PLUS);
533 	default:
534 		break;
535 	}
536 	return (LIBUSB_SPEED_UNKNOWN);
537 }
538 
539 static const libusb_endpoint_descriptor *
540 libusb_get_endpoint_from_config(libusb_config_descriptor *pdconf,
541     uint8_t endpoint)
542 {
543 	struct libusb_interface *pinf;
544 	struct libusb_interface_descriptor *pdinf;
545 	const struct libusb_endpoint_descriptor *pdend;
546 	int i;
547 	int j;
548 	int k;
549 
550 	for (i = 0; i < pdconf->bNumInterfaces; i++) {
551 		pinf = &pdconf->interface[i];
552 		for (j = 0; j < pinf->num_altsetting; j++) {
553 			pdinf = &pinf->altsetting[j];
554 			for (k = 0; k < pdinf->bNumEndpoints; k++) {
555 				pdend = &pdinf->endpoint[k];
556 				if (pdend->bEndpointAddress == endpoint) {
557 					return (pdend);
558 				}
559 			}
560 		}
561 	}
562 
563 	return (NULL);
564 }
565 
566 int
567 libusb_get_max_packet_size(libusb_device *dev, uint8_t endpoint)
568 {
569 	struct libusb_config_descriptor *pdconf;
570 	const struct libusb_endpoint_descriptor *pdend;
571 	int ret;
572 
573 	if (dev == NULL)
574 		return (LIBUSB_ERROR_OTHER);
575 
576 	ret = libusb_get_active_config_descriptor(dev, &pdconf);
577 	if (ret < 0)
578 		return (ret);
579 
580 	ret = LIBUSB_ERROR_NOT_FOUND;
581 	if ((pdend = libusb_get_endpoint_from_config(pdconf, endpoint)) != NULL)
582 		ret = pdend->wMaxPacketSize;
583 
584 	libusb_free_config_descriptor(pdconf);
585 	return (ret);
586 }
587 
588 static int
589 libusb_calculate_ep_size(libusb_device *dev,
590     const libusb_endpoint_descriptor *ep)
591 {
592 	struct libusb_ss_endpoint_companion_descriptor *ss_ep;
593 	int multiplier;
594 	int speed;
595 	int ret = LIBUSB_ERROR_NOT_SUPPORTED;
596 	enum libusb_endpoint_transfer_type type;
597 
598 	speed = libusb_get_device_speed(dev);
599 	if (speed >= LIBUSB_SPEED_SUPER) {
600 		ret = libusb_get_ss_endpoint_companion_descriptor(dev->ctx, ep,
601 		    &ss_ep);
602 		if (ret == LIBUSB_SUCCESS) {
603 			ret = ss_ep->wBytesPerInterval;
604 			libusb_free_ss_endpoint_companion_descriptor(ss_ep);
605 		}
606 	}
607 
608 	/*
609 	 * reference:
610 	 * https://www.keil.com/pack/doc/mw/usb/html/_u_s_b__endpoint__descriptor.html
611 	 */
612 	if (ret < 0) {
613 		ret = ep->wMaxPacketSize;
614 		switch (speed) {
615 		case LIBUSB_SPEED_LOW:
616 		case LIBUSB_SPEED_FULL:
617 			break;
618 		default:
619 			type = ep->bmAttributes & 0x3;
620 			if (type == LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS ||
621 			    type == LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT) {
622 				multiplier = (1 + ((ret >> 11) & 3));
623 				if (multiplier > 3)
624 					multiplier = 3;
625 				ret = (ret & 0x7FF) * multiplier;
626 			}
627 			break;
628 		}
629 	}
630 
631 	return (ret);
632 }
633 
634 int
635 libusb_get_max_iso_packet_size(libusb_device *dev, uint8_t endpoint)
636 {
637 	struct libusb_config_descriptor *pdconf;
638 	const struct libusb_endpoint_descriptor *pdend;
639 	int ret;
640 
641 	if (dev == NULL)
642 		return (LIBUSB_ERROR_OTHER);
643 
644 	ret = libusb_get_active_config_descriptor(dev, &pdconf);
645 	if (ret < 0)
646 		return (LIBUSB_ERROR_OTHER);
647 
648 	pdend = libusb_get_endpoint_from_config(pdconf, endpoint);
649 	if (pdend == NULL) {
650 		libusb_free_config_descriptor(pdconf);
651 		return (LIBUSB_ERROR_NOT_FOUND);
652 	}
653 
654 	ret = libusb_calculate_ep_size(dev, pdend);
655 	libusb_free_config_descriptor(pdconf);
656 	return (ret);
657 }
658 
659 int
660 libusb_get_max_alt_packet_size(libusb_device *dev, int interface_number,
661     int alternate_setting, unsigned char endpoint)
662 {
663 	struct libusb_config_descriptor *pdconf;
664 	struct libusb_interface *pinf;
665 	struct libusb_interface_descriptor *pdinf;
666 	const struct libusb_endpoint_descriptor *pdend = NULL;
667 	const struct libusb_endpoint_descriptor *pdend_tmp;
668 	int ret, i;
669 
670 	if (dev == NULL)
671 		return (LIBUSB_ERROR_OTHER);
672 
673 	ret = libusb_get_active_config_descriptor(dev, &pdconf);
674 	if (ret < 0)
675 		return (LIBUSB_ERROR_OTHER);
676 
677 	if (pdconf->bNumInterfaces <= interface_number) {
678 		libusb_free_config_descriptor(pdconf);
679 		return (LIBUSB_ERROR_NOT_FOUND);
680 	}
681 	pinf = &pdconf->interface[interface_number];
682 
683 	if (pinf->num_altsetting <= alternate_setting) {
684 		libusb_free_config_descriptor(pdconf);
685 		return (LIBUSB_ERROR_NOT_FOUND);
686 	}
687 	pdinf = &pinf->altsetting[alternate_setting];
688 
689 	for (i = 0; i < pdinf->bNumEndpoints; ++i) {
690 		pdend_tmp = &pdinf->endpoint[i];
691 		if (pdend_tmp->bEndpointAddress == endpoint) {
692 			pdend = pdend_tmp;
693 			break;
694 		}
695 	}
696 	if (pdend != NULL)
697 		ret = libusb_calculate_ep_size(dev, pdend);
698 	else
699 		ret = LIBUSB_ERROR_NOT_FOUND;
700 	libusb_free_config_descriptor(pdconf);
701 
702 	return (ret);
703 }
704 
705 libusb_device *
706 libusb_ref_device(libusb_device *dev)
707 {
708 	if (dev == NULL)
709 		return (NULL);		/* be NULL safe */
710 
711 	CTX_LOCK(dev->ctx);
712 	dev->refcnt++;
713 	CTX_UNLOCK(dev->ctx);
714 
715 	return (dev);
716 }
717 
718 void
719 libusb_unref_device(libusb_device *dev)
720 {
721 	if (dev == NULL)
722 		return;			/* be NULL safe */
723 
724 	CTX_LOCK(dev->ctx);
725 	dev->refcnt--;
726 	CTX_UNLOCK(dev->ctx);
727 
728 	if (dev->refcnt == 0) {
729 		libusb_unref_device(dev->parent_dev);
730 		libusb20_dev_free(dev->os_priv);
731 		free(dev);
732 	}
733 }
734 
735 int
736 libusb_open(libusb_device *dev, libusb_device_handle **devh)
737 {
738 	libusb_context *ctx = dev->ctx;
739 	struct libusb20_device *pdev = dev->os_priv;
740 	int err;
741 
742 	if (devh == NULL)
743 		return (LIBUSB_ERROR_INVALID_PARAM);
744 
745 	/* set default device handle value */
746 	*devh = NULL;
747 
748 	dev = libusb_ref_device(dev);
749 	if (dev == NULL)
750 		return (LIBUSB_ERROR_INVALID_PARAM);
751 
752 	err = libusb20_dev_open(pdev, LIBUSB_NUM_SW_ENDPOINTS);
753 	if (err) {
754 		libusb_unref_device(dev);
755 		return (LIBUSB_ERROR_NO_MEM);
756 	}
757 
758 	/*
759 	 * Clear the device gone flag, in case the device was opened
760 	 * after a re-attach, to allow new transaction:
761 	 */
762 	CTX_LOCK(ctx);
763 	dev->device_is_gone = 0;
764 	CTX_UNLOCK(ctx);
765 
766 	libusb10_add_pollfd(ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
767 	    POLLOUT | POLLRDNORM | POLLWRNORM);
768 
769 	/* make sure our event loop detects the new device */
770 	libusb_interrupt_event_handler(ctx);
771 
772 	*devh = pdev;
773 
774 	return (0);
775 }
776 
777 libusb_device_handle *
778 libusb_open_device_with_vid_pid(libusb_context *ctx, uint16_t vendor_id,
779     uint16_t product_id)
780 {
781 	struct libusb_device **devs;
782 	struct libusb20_device *pdev;
783 	struct LIBUSB20_DEVICE_DESC_DECODED *pdesc;
784 	int i;
785 	int j;
786 
787 	ctx = GET_CONTEXT(ctx);
788 	if (ctx == NULL)
789 		return (NULL);		/* be NULL safe */
790 
791 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_open_device_with_vid_pid enter");
792 
793 	if ((i = libusb_get_device_list(ctx, &devs)) < 0)
794 		return (NULL);
795 
796 	pdev = NULL;
797 	for (j = 0; j < i; j++) {
798 		struct libusb20_device *tdev;
799 
800 		tdev = devs[j]->os_priv;
801 		pdesc = libusb20_dev_get_device_desc(tdev);
802 		/*
803 		 * NOTE: The USB library will automatically swap the
804 		 * fields in the device descriptor to be of host
805 		 * endian type!
806 		 */
807 		if (pdesc->idVendor == vendor_id &&
808 		    pdesc->idProduct == product_id) {
809 			libusb_open(devs[j], &pdev);
810 			break;
811 		}
812 	}
813 
814 	libusb_free_device_list(devs, 1);
815 	DPRINTF(ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_open_device_with_vid_pid leave");
816 	return (pdev);
817 }
818 
819 void
820 libusb_close(struct libusb20_device *pdev)
821 {
822 	libusb_context *ctx;
823 	struct libusb_device *dev;
824 
825 	if (pdev == NULL)
826 		return;			/* be NULL safe */
827 
828 	dev = libusb_get_device(pdev);
829 	ctx = dev->ctx;
830 
831 	libusb10_remove_pollfd(ctx, &dev->dev_poll);
832 
833 	libusb20_dev_close(pdev);
834 
835 	/* unref will free the "pdev" when the refcount reaches zero */
836 	libusb_unref_device(dev);
837 
838 	/* make sure our event loop detects the closed device */
839 	libusb_interrupt_event_handler(ctx);
840 }
841 
842 libusb_device *
843 libusb_get_device(struct libusb20_device *pdev)
844 {
845 	if (pdev == NULL)
846 		return (NULL);
847 	return ((libusb_device *)pdev->privLuData);
848 }
849 
850 int
851 libusb_get_configuration(struct libusb20_device *pdev, int *config)
852 {
853 	struct libusb20_config *pconf;
854 
855 	if (pdev == NULL || config == NULL)
856 		return (LIBUSB_ERROR_INVALID_PARAM);
857 
858 	pconf = libusb20_dev_alloc_config(pdev, libusb20_dev_get_config_index(pdev));
859 	if (pconf == NULL)
860 		return (LIBUSB_ERROR_NO_MEM);
861 
862 	*config = pconf->desc.bConfigurationValue;
863 
864 	free(pconf);
865 
866 	return (0);
867 }
868 
869 int
870 libusb_set_configuration(struct libusb20_device *pdev, int configuration)
871 {
872 	struct libusb20_config *pconf;
873 	struct libusb_device *dev;
874 	int err;
875 	uint8_t i;
876 
877 	dev = libusb_get_device(pdev);
878 	if (dev == NULL)
879 		return (LIBUSB_ERROR_INVALID_PARAM);
880 
881 	if (configuration < 1) {
882 		/* unconfigure */
883 		i = 255;
884 	} else {
885 		for (i = 0; i != 255; i++) {
886 			uint8_t found;
887 
888 			pconf = libusb20_dev_alloc_config(pdev, i);
889 			if (pconf == NULL)
890 				return (LIBUSB_ERROR_INVALID_PARAM);
891 			found = (pconf->desc.bConfigurationValue
892 			    == configuration);
893 			free(pconf);
894 
895 			if (found)
896 				goto set_config;
897 		}
898 		return (LIBUSB_ERROR_INVALID_PARAM);
899 	}
900 
901 set_config:
902 
903 	libusb10_cancel_all_transfer(dev);
904 
905 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
906 
907 	err = libusb20_dev_set_config_index(pdev, i);
908 
909 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll, pdev, libusb20_dev_get_fd(pdev), POLLIN |
910 	    POLLOUT | POLLRDNORM | POLLWRNORM);
911 
912 	return (err ? LIBUSB_ERROR_INVALID_PARAM : 0);
913 }
914 
915 int
916 libusb_claim_interface(struct libusb20_device *pdev, int interface_number)
917 {
918 	libusb_device *dev;
919 	int err = 0;
920 
921 	dev = libusb_get_device(pdev);
922 	if (dev == NULL)
923 		return (LIBUSB_ERROR_INVALID_PARAM);
924 
925 	if (interface_number < 0 || interface_number > 31)
926 		return (LIBUSB_ERROR_INVALID_PARAM);
927 
928 	if (pdev->auto_detach != 0) {
929 		err = libusb_detach_kernel_driver(pdev, interface_number);
930 		if (err != 0)
931 			goto done;
932 	}
933 
934 	CTX_LOCK(dev->ctx);
935 	dev->claimed_interfaces |= (1 << interface_number);
936 	CTX_UNLOCK(dev->ctx);
937 done:
938 	return (err);
939 }
940 
941 int
942 libusb_release_interface(struct libusb20_device *pdev, int interface_number)
943 {
944 	libusb_device *dev;
945 	int err = 0;
946 
947 	dev = libusb_get_device(pdev);
948 	if (dev == NULL)
949 		return (LIBUSB_ERROR_INVALID_PARAM);
950 
951 	if (interface_number < 0 || interface_number > 31)
952 		return (LIBUSB_ERROR_INVALID_PARAM);
953 
954 	if (pdev->auto_detach != 0) {
955 		err = libusb_attach_kernel_driver(pdev, interface_number);
956 		if (err != 0)
957 			goto done;
958 	}
959 
960 	CTX_LOCK(dev->ctx);
961 	if (!(dev->claimed_interfaces & (1 << interface_number)))
962 		err = LIBUSB_ERROR_NOT_FOUND;
963 	else
964 		dev->claimed_interfaces &= ~(1 << interface_number);
965 	CTX_UNLOCK(dev->ctx);
966 done:
967 	return (err);
968 }
969 
970 int
971 libusb_set_interface_alt_setting(struct libusb20_device *pdev,
972     int interface_number, int alternate_setting)
973 {
974 	libusb_device *dev;
975 	int err = 0;
976 
977 	dev = libusb_get_device(pdev);
978 	if (dev == NULL)
979 		return (LIBUSB_ERROR_INVALID_PARAM);
980 
981 	if (interface_number < 0 || interface_number > 31)
982 		return (LIBUSB_ERROR_INVALID_PARAM);
983 
984 	CTX_LOCK(dev->ctx);
985 	if (!(dev->claimed_interfaces & (1 << interface_number)))
986 		err = LIBUSB_ERROR_NOT_FOUND;
987 	CTX_UNLOCK(dev->ctx);
988 
989 	if (err)
990 		return (err);
991 
992 	libusb10_cancel_all_transfer(dev);
993 
994 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
995 
996 	err = libusb20_dev_set_alt_index(pdev,
997 	    interface_number, alternate_setting);
998 
999 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
1000 	    pdev, libusb20_dev_get_fd(pdev),
1001 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
1002 
1003 	return (err ? LIBUSB_ERROR_OTHER : 0);
1004 }
1005 
1006 libusb_device *
1007 libusb_get_parent(libusb_device *dev)
1008 {
1009 	return (dev->parent_dev);
1010 }
1011 
1012 static struct libusb20_transfer *
1013 libusb10_get_transfer(struct libusb20_device *pdev,
1014     uint8_t endpoint, uint8_t xfer_index)
1015 {
1016 	xfer_index &= 1;	/* double buffering */
1017 
1018 	xfer_index |= (endpoint & LIBUSB20_ENDPOINT_ADDRESS_MASK) * 4;
1019 
1020 	if (endpoint & LIBUSB20_ENDPOINT_DIR_MASK) {
1021 		/* this is an IN endpoint */
1022 		xfer_index |= 2;
1023 	}
1024 	return (libusb20_tr_get_pointer(pdev, xfer_index));
1025 }
1026 
1027 int
1028 libusb_clear_halt(struct libusb20_device *pdev, uint8_t endpoint)
1029 {
1030 	struct libusb20_transfer *xfer;
1031 	struct libusb_device *dev;
1032 	int err;
1033 
1034 	xfer = libusb10_get_transfer(pdev, endpoint, 0);
1035 	if (xfer == NULL)
1036 		return (LIBUSB_ERROR_INVALID_PARAM);
1037 
1038 	dev = libusb_get_device(pdev);
1039 	if (dev == NULL)
1040 		return (LIBUSB_ERROR_INVALID_PARAM);
1041 
1042 	CTX_LOCK(dev->ctx);
1043 	err = libusb20_tr_open(xfer, 0, 1, endpoint);
1044 	CTX_UNLOCK(dev->ctx);
1045 
1046 	if (err != 0 && err != LIBUSB20_ERROR_BUSY)
1047 		return (LIBUSB_ERROR_OTHER);
1048 
1049 	libusb20_tr_clear_stall_sync(xfer);
1050 
1051 	/* check if we opened the transfer */
1052 	if (err == 0) {
1053 		CTX_LOCK(dev->ctx);
1054 		libusb20_tr_close(xfer);
1055 		CTX_UNLOCK(dev->ctx);
1056 	}
1057 	return (0);			/* success */
1058 }
1059 
1060 int
1061 libusb_reset_device(struct libusb20_device *pdev)
1062 {
1063 	libusb_device *dev;
1064 	int err;
1065 
1066 	dev = libusb_get_device(pdev);
1067 	if (dev == NULL)
1068 		return (LIBUSB_ERROR_INVALID_PARAM);
1069 
1070 	libusb10_cancel_all_transfer(dev);
1071 
1072 	libusb10_remove_pollfd(dev->ctx, &dev->dev_poll);
1073 
1074 	err = libusb20_dev_reset(pdev);
1075 
1076 	libusb10_add_pollfd(dev->ctx, &dev->dev_poll,
1077 	    pdev, libusb20_dev_get_fd(pdev),
1078 	    POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
1079 
1080 	return (err ? LIBUSB_ERROR_OTHER : 0);
1081 }
1082 
1083 int
1084 libusb_check_connected(struct libusb20_device *pdev)
1085 {
1086 	libusb_device *dev;
1087 	int err;
1088 
1089 	dev = libusb_get_device(pdev);
1090 	if (dev == NULL)
1091 		return (LIBUSB_ERROR_INVALID_PARAM);
1092 
1093 	err = libusb20_dev_check_connected(pdev);
1094 
1095 	return (err ? LIBUSB_ERROR_NO_DEVICE : 0);
1096 }
1097 
1098 int
1099 libusb_kernel_driver_active(struct libusb20_device *pdev, int interface)
1100 {
1101 	if (pdev == NULL)
1102 		return (LIBUSB_ERROR_INVALID_PARAM);
1103 
1104 	if (libusb20_dev_kernel_driver_active(pdev, interface))
1105 		return (0);		/* no kernel driver is active */
1106 	else
1107 		return (1);		/* kernel driver is active */
1108 }
1109 
1110 int
1111 libusb_get_driver_np(struct libusb20_device *pdev, int interface,
1112     char *name, int namelen)
1113 {
1114 	return (libusb_get_driver(pdev, interface, name, namelen));
1115 }
1116 
1117 int
1118 libusb_get_driver(struct libusb20_device *pdev, int interface,
1119     char *name, int namelen)
1120 {
1121 	char *ptr;
1122 	int err;
1123 
1124 	if (pdev == NULL)
1125 		return (LIBUSB_ERROR_INVALID_PARAM);
1126 	if (namelen < 1)
1127 		return (LIBUSB_ERROR_INVALID_PARAM);
1128 	if (namelen > 255)
1129 		namelen = 255;
1130 
1131 	err = libusb20_dev_get_iface_desc(
1132 	    pdev, interface, name, namelen);
1133 
1134 	if (err != 0)
1135 		return (LIBUSB_ERROR_OTHER);
1136 
1137 	/* we only want the driver name */
1138 	ptr = strstr(name, ":");
1139 	if (ptr != NULL)
1140 		*ptr = 0;
1141 
1142 	return (0);
1143 }
1144 
1145 int
1146 libusb_detach_kernel_driver_np(struct libusb20_device *pdev, int interface)
1147 {
1148 	return (libusb_detach_kernel_driver(pdev, interface));
1149 }
1150 
1151 int
1152 libusb_detach_kernel_driver(struct libusb20_device *pdev, int interface)
1153 {
1154 	int err;
1155 
1156 	if (pdev == NULL)
1157 		return (LIBUSB_ERROR_INVALID_PARAM);
1158 
1159 	err = libusb20_dev_detach_kernel_driver(
1160 	    pdev, interface);
1161 
1162 	return (err ? LIBUSB_ERROR_OTHER : 0);
1163 }
1164 
1165 int
1166 libusb_attach_kernel_driver(struct libusb20_device *pdev, int interface)
1167 {
1168 	int err;
1169 
1170 	if (pdev == NULL)
1171 		return (LIBUSB_ERROR_INVALID_PARAM);
1172 
1173 	err = libusb20_dev_attach_kernel_driver(pdev, interface);
1174 
1175 	return (err ? LIBUSB_ERROR_OTHER : 0);
1176 }
1177 
1178 int
1179 libusb_set_auto_detach_kernel_driver(libusb_device_handle *dev, int enable)
1180 {
1181 	dev->auto_detach = (enable ? 1 : 0);
1182 	return (0);
1183 }
1184 
1185 /* Asynchronous device I/O */
1186 
1187 struct libusb_transfer *
1188 libusb_alloc_transfer(int iso_packets)
1189 {
1190 	struct libusb_transfer *uxfer;
1191 	struct libusb_super_transfer *sxfer;
1192 	int len;
1193 
1194 	len = sizeof(struct libusb_transfer) +
1195 	    sizeof(struct libusb_super_transfer) +
1196 	    (iso_packets * sizeof(libusb_iso_packet_descriptor));
1197 
1198 	sxfer = malloc(len);
1199 	if (sxfer == NULL)
1200 		return (NULL);
1201 
1202 	memset(sxfer, 0, len);
1203 
1204 	uxfer = (struct libusb_transfer *)(
1205 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1206 
1207 	/* set default value */
1208 	uxfer->num_iso_packets = iso_packets;
1209 
1210 	return (uxfer);
1211 }
1212 
1213 void
1214 libusb_free_transfer(struct libusb_transfer *uxfer)
1215 {
1216 	struct libusb_super_transfer *sxfer;
1217 
1218 	if (uxfer == NULL)
1219 		return;			/* be NULL safe */
1220 
1221 	/* check if we should free the transfer buffer */
1222 	if (uxfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
1223 		free(uxfer->buffer);
1224 
1225 	sxfer = (struct libusb_super_transfer *)(
1226 	    (uint8_t *)uxfer - sizeof(*sxfer));
1227 
1228 	free(sxfer);
1229 }
1230 
1231 static uint32_t
1232 libusb10_get_maxframe(struct libusb20_device *pdev, libusb_transfer *xfer)
1233 {
1234 	uint32_t ret;
1235 
1236 	switch (xfer->type) {
1237 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1238 		ret = 60 | LIBUSB20_MAX_FRAME_PRE_SCALE;	/* 60ms */
1239 		break;
1240 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1241 		ret = 2;
1242 		break;
1243 	default:
1244 		ret = 1;
1245 		break;
1246 	}
1247 	return (ret);
1248 }
1249 
1250 static int
1251 libusb10_get_buffsize(struct libusb20_device *pdev, libusb_transfer *xfer)
1252 {
1253 	int ret;
1254 	int usb_speed;
1255 
1256 	usb_speed = libusb20_dev_get_speed(pdev);
1257 
1258 	switch (xfer->type) {
1259 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1260 		ret = 0;		/* kernel will auto-select */
1261 		break;
1262 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1263 		ret = 1024;
1264 		break;
1265 	default:
1266 		switch (usb_speed) {
1267 		case LIBUSB20_SPEED_LOW:
1268 			ret = 256;
1269 			break;
1270 		case LIBUSB20_SPEED_FULL:
1271 			ret = 4096;
1272 			break;
1273 		case LIBUSB20_SPEED_SUPER:
1274 			ret = 65536;
1275 			break;
1276 		case LIBUSB20_SPEED_SUPER_PLUS:
1277 			ret = 131072;
1278 			break;
1279 		default:
1280 			ret = 16384;
1281 			break;
1282 		}
1283 		break;
1284 	}
1285 	return (ret);
1286 }
1287 
1288 static int
1289 libusb10_convert_error(uint8_t status)
1290 {
1291 	;				/* indent fix */
1292 
1293 	switch (status) {
1294 	case LIBUSB20_TRANSFER_START:
1295 	case LIBUSB20_TRANSFER_COMPLETED:
1296 		return (LIBUSB_TRANSFER_COMPLETED);
1297 	case LIBUSB20_TRANSFER_OVERFLOW:
1298 		return (LIBUSB_TRANSFER_OVERFLOW);
1299 	case LIBUSB20_TRANSFER_NO_DEVICE:
1300 		return (LIBUSB_TRANSFER_NO_DEVICE);
1301 	case LIBUSB20_TRANSFER_STALL:
1302 		return (LIBUSB_TRANSFER_STALL);
1303 	case LIBUSB20_TRANSFER_CANCELLED:
1304 		return (LIBUSB_TRANSFER_CANCELLED);
1305 	case LIBUSB20_TRANSFER_TIMED_OUT:
1306 		return (LIBUSB_TRANSFER_TIMED_OUT);
1307 	default:
1308 		return (LIBUSB_TRANSFER_ERROR);
1309 	}
1310 }
1311 
1312 /* This function must be called locked */
1313 
1314 static void
1315 libusb10_complete_transfer(struct libusb20_transfer *pxfer,
1316     struct libusb_super_transfer *sxfer, int status)
1317 {
1318 	struct libusb_transfer *uxfer;
1319 	struct libusb_device *dev;
1320 
1321 	uxfer = (struct libusb_transfer *)(
1322 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1323 
1324 	if (pxfer != NULL)
1325 		libusb20_tr_set_priv_sc1(pxfer, NULL);
1326 
1327 	/* set transfer status */
1328 	uxfer->status = status;
1329 
1330 	/* update super transfer state */
1331 	sxfer->state = LIBUSB_SUPER_XFER_ST_NONE;
1332 
1333 	dev = libusb_get_device(uxfer->dev_handle);
1334 
1335 	TAILQ_INSERT_TAIL(&dev->ctx->tr_done, sxfer, entry);
1336 }
1337 
1338 /* This function must be called locked */
1339 
1340 static void
1341 libusb10_isoc_proxy(struct libusb20_transfer *pxfer)
1342 {
1343 	struct libusb_super_transfer *sxfer;
1344 	struct libusb_transfer *uxfer;
1345 	uint32_t actlen;
1346 	uint16_t iso_packets;
1347 	uint16_t i;
1348 	uint8_t status;
1349 
1350 	status = libusb20_tr_get_status(pxfer);
1351 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1352 	actlen = libusb20_tr_get_actual_length(pxfer);
1353 	iso_packets = libusb20_tr_get_max_frames(pxfer);
1354 
1355 	if (sxfer == NULL)
1356 		return; /* cancelled - nothing to do */
1357 
1358 	uxfer = (struct libusb_transfer *)(
1359 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1360 
1361 	if (iso_packets > uxfer->num_iso_packets)
1362 		iso_packets = uxfer->num_iso_packets;
1363 
1364 	if (iso_packets == 0)
1365 		return; /* nothing to do */
1366 
1367 	/* make sure that the number of ISOCHRONOUS packets is valid */
1368 	uxfer->num_iso_packets = iso_packets;
1369 
1370 	switch (status) {
1371 	case LIBUSB20_TRANSFER_COMPLETED:
1372 		/* update actual length */
1373 		uxfer->actual_length = actlen;
1374 		for (i = 0; i != iso_packets; i++) {
1375 			uxfer->iso_packet_desc[i].actual_length =
1376 			    libusb20_tr_get_length(pxfer, i);
1377 		}
1378 		libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1379 
1380 		/* start next queued transfer, if any */
1381 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1382 		break;
1383 	case LIBUSB20_TRANSFER_START:
1384 		/* setup length(s) */
1385 		actlen = 0;
1386 		for (i = 0; i != iso_packets; i++) {
1387 			libusb20_tr_setup_isoc(pxfer,
1388 			    &uxfer->buffer[actlen],
1389 			    uxfer->iso_packet_desc[i].length, i);
1390 			actlen += uxfer->iso_packet_desc[i].length;
1391 		}
1392 
1393 		/* no remainder */
1394 		sxfer->rem_len = 0;
1395 
1396 		libusb20_tr_set_total_frames(pxfer, iso_packets);
1397 		libusb20_tr_submit(pxfer);
1398 
1399 		/* fork another USB transfer, if any */
1400 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1401 		break;
1402 	default:
1403 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1404 
1405 		/* start next queued transfer, if any */
1406 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1407 		break;
1408 	}
1409 }
1410 
1411 /* This function must be called locked */
1412 
1413 static void
1414 libusb10_bulk_intr_proxy(struct libusb20_transfer *pxfer)
1415 {
1416 	struct libusb_super_transfer *sxfer;
1417 	struct libusb_transfer *uxfer;
1418 	uint32_t max_bulk;
1419 	uint32_t actlen;
1420 	uint8_t status;
1421 	uint8_t flags;
1422 	uint8_t tr_flags;
1423 
1424 	status = libusb20_tr_get_status(pxfer);
1425 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1426 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1427 	actlen = libusb20_tr_get_actual_length(pxfer);
1428 
1429 	if (sxfer == NULL)
1430 		return;			/* cancelled - nothing to do */
1431 
1432 	uxfer = (struct libusb_transfer *)(
1433 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1434 
1435 	flags = uxfer->flags;
1436 
1437 	switch (status) {
1438 	case LIBUSB20_TRANSFER_COMPLETED:
1439 
1440 		uxfer->actual_length += actlen;
1441 
1442 		/* check for short packet */
1443 		if (sxfer->last_len != actlen) {
1444 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1445 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1446 			} else {
1447 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1448 			}
1449 			/* start next queued transfer, if any */
1450 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1451 			break;
1452 		}
1453 		/* check for end of data */
1454 		if (sxfer->rem_len == 0) {
1455 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1456 			/* start next queued transfer, if any */
1457 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1458 			break;
1459 		}
1460 		/* FALLTHROUGH */
1461 
1462 	case LIBUSB20_TRANSFER_START:
1463 		if (max_bulk > sxfer->rem_len) {
1464 			max_bulk = sxfer->rem_len;
1465 		}
1466 		/* setup new BULK or INTERRUPT transaction */
1467 		libusb20_tr_setup_bulk(pxfer,
1468 		    sxfer->curr_data, max_bulk, uxfer->timeout);
1469 
1470 		/* update counters */
1471 		sxfer->last_len = max_bulk;
1472 		sxfer->curr_data += max_bulk;
1473 		sxfer->rem_len -= max_bulk;
1474 
1475 		/*
1476 		 * When a zero length packet (ZLP) is requested, ask the
1477 		 * kernel to terminate the last frame of the transfer with
1478 		 * a short packet. This appends a ZLP when the data length
1479 		 * is an exact multiple of the maximum packet size.
1480 		 */
1481 		tr_flags = libusb20_tr_get_flags(pxfer);
1482 		if (sxfer->rem_len == 0 &&
1483 		    (flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1484 			tr_flags |= LIBUSB20_TRANSFER_FORCE_SHORT;
1485 		else
1486 			tr_flags &= ~LIBUSB20_TRANSFER_FORCE_SHORT;
1487 		libusb20_tr_set_flags(pxfer, tr_flags);
1488 
1489 		libusb20_tr_submit(pxfer);
1490 
1491 		/* check if we can fork another USB transfer */
1492 		if (sxfer->rem_len == 0)
1493 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1494 		break;
1495 
1496 	default:
1497 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1498 		/* start next queued transfer, if any */
1499 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1500 		break;
1501 	}
1502 }
1503 
1504 /* This function must be called locked */
1505 
1506 static void
1507 libusb10_ctrl_proxy(struct libusb20_transfer *pxfer)
1508 {
1509 	struct libusb_super_transfer *sxfer;
1510 	struct libusb_transfer *uxfer;
1511 	uint32_t max_bulk;
1512 	uint32_t actlen;
1513 	uint8_t status;
1514 	uint8_t flags;
1515 
1516 	status = libusb20_tr_get_status(pxfer);
1517 	sxfer = libusb20_tr_get_priv_sc1(pxfer);
1518 	max_bulk = libusb20_tr_get_max_total_length(pxfer);
1519 	actlen = libusb20_tr_get_actual_length(pxfer);
1520 
1521 	if (sxfer == NULL)
1522 		return;			/* cancelled - nothing to do */
1523 
1524 	uxfer = (struct libusb_transfer *)(
1525 	    ((uint8_t *)sxfer) + sizeof(*sxfer));
1526 
1527 	flags = uxfer->flags;
1528 
1529 	switch (status) {
1530 	case LIBUSB20_TRANSFER_COMPLETED:
1531 
1532 		uxfer->actual_length += actlen;
1533 
1534 		/* subtract length of SETUP packet, if any */
1535 		actlen -= libusb20_tr_get_length(pxfer, 0);
1536 
1537 		/* check for short packet */
1538 		if (sxfer->last_len != actlen) {
1539 			if (flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1540 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_ERROR);
1541 			} else {
1542 				libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1543 			}
1544 			/* start next queued transfer, if any */
1545 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1546 			break;
1547 		}
1548 		/* check for end of data */
1549 		if (sxfer->rem_len == 0) {
1550 			libusb10_complete_transfer(pxfer, sxfer, LIBUSB_TRANSFER_COMPLETED);
1551 			/* start next queued transfer, if any */
1552 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1553 			break;
1554 		}
1555 		/* FALLTHROUGH */
1556 
1557 	case LIBUSB20_TRANSFER_START:
1558 		if (max_bulk > sxfer->rem_len) {
1559 			max_bulk = sxfer->rem_len;
1560 		}
1561 		/* setup new CONTROL transaction */
1562 		if (status == LIBUSB20_TRANSFER_COMPLETED) {
1563 			/* next fragment - don't send SETUP packet */
1564 			libusb20_tr_set_length(pxfer, 0, 0);
1565 		} else {
1566 			/* first fragment - send SETUP packet */
1567 			libusb20_tr_set_length(pxfer, 8, 0);
1568 			libusb20_tr_set_buffer(pxfer, uxfer->buffer, 0);
1569 		}
1570 
1571 		if (max_bulk != 0) {
1572 			libusb20_tr_set_length(pxfer, max_bulk, 1);
1573 			libusb20_tr_set_buffer(pxfer, sxfer->curr_data, 1);
1574 			libusb20_tr_set_total_frames(pxfer, 2);
1575 		} else {
1576 			libusb20_tr_set_total_frames(pxfer, 1);
1577 		}
1578 
1579 		/* update counters */
1580 		sxfer->last_len = max_bulk;
1581 		sxfer->curr_data += max_bulk;
1582 		sxfer->rem_len -= max_bulk;
1583 
1584 		libusb20_tr_submit(pxfer);
1585 
1586 		/* check if we can fork another USB transfer */
1587 		if (sxfer->rem_len == 0)
1588 			libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1589 		break;
1590 
1591 	default:
1592 		libusb10_complete_transfer(pxfer, sxfer, libusb10_convert_error(status));
1593 		/* start next queued transfer, if any */
1594 		libusb10_submit_transfer_sub(libusb20_tr_get_priv_sc0(pxfer), uxfer->endpoint);
1595 		break;
1596 	}
1597 }
1598 
1599 /* The following function must be called locked */
1600 
1601 static void
1602 libusb10_submit_transfer_sub(struct libusb20_device *pdev, uint8_t endpoint)
1603 {
1604 	struct libusb20_transfer *pxfer0;
1605 	struct libusb20_transfer *pxfer1;
1606 	struct libusb_super_transfer *sxfer;
1607 	struct libusb_transfer *uxfer;
1608 	struct libusb_device *dev;
1609 	int err;
1610 	int buffsize;
1611 	int maxframe;
1612 	int temp;
1613 
1614 	dev = libusb_get_device(pdev);
1615 
1616 	pxfer0 = libusb10_get_transfer(pdev, endpoint, 0);
1617 	pxfer1 = libusb10_get_transfer(pdev, endpoint, 1);
1618 
1619 	if (pxfer0 == NULL || pxfer1 == NULL)
1620 		return;			/* shouldn't happen */
1621 
1622 	temp = 0;
1623 	if (libusb20_tr_pending(pxfer0))
1624 		temp |= 1;
1625 	if (libusb20_tr_pending(pxfer1))
1626 		temp |= 2;
1627 
1628 	switch (temp) {
1629 	case 3:
1630 		/* wait till one of the transfers complete */
1631 		return;
1632 	case 2:
1633 		sxfer = libusb20_tr_get_priv_sc1(pxfer1);
1634 		if (sxfer == NULL)
1635 			return;		/* cancelling */
1636 		if (sxfer->rem_len)
1637 			return;		/* cannot queue another one */
1638 		/* swap transfers */
1639 		pxfer1 = pxfer0;
1640 		break;
1641 	case 1:
1642 		sxfer = libusb20_tr_get_priv_sc1(pxfer0);
1643 		if (sxfer == NULL)
1644 			return;		/* cancelling */
1645 		if (sxfer->rem_len)
1646 			return;		/* cannot queue another one */
1647 		/* swap transfers */
1648 		pxfer0 = pxfer1;
1649 		break;
1650 	default:
1651 		break;
1652 	}
1653 
1654 	/* find next transfer on same endpoint */
1655 	TAILQ_FOREACH(sxfer, &dev->tr_head, entry) {
1656 
1657 		uxfer = (struct libusb_transfer *)(
1658 		    ((uint8_t *)sxfer) + sizeof(*sxfer));
1659 
1660 		if (uxfer->endpoint == endpoint) {
1661 			TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1662 			sxfer->entry.tqe_prev = NULL;
1663 			goto found;
1664 		}
1665 	}
1666 	return;				/* success */
1667 
1668 found:
1669 
1670 	libusb20_tr_set_priv_sc0(pxfer0, pdev);
1671 	libusb20_tr_set_priv_sc1(pxfer0, sxfer);
1672 
1673 	/* reset super transfer state */
1674 	sxfer->rem_len = uxfer->length;
1675 	sxfer->curr_data = uxfer->buffer;
1676 	uxfer->actual_length = 0;
1677 
1678 	switch (uxfer->type) {
1679 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1680 		libusb20_tr_set_callback(pxfer0, libusb10_isoc_proxy);
1681 		break;
1682 	case LIBUSB_TRANSFER_TYPE_BULK:
1683 	case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1684 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1685 		libusb20_tr_set_callback(pxfer0, libusb10_bulk_intr_proxy);
1686 		break;
1687 	case LIBUSB_TRANSFER_TYPE_CONTROL:
1688 		libusb20_tr_set_callback(pxfer0, libusb10_ctrl_proxy);
1689 		if (sxfer->rem_len < 8)
1690 			goto failure;
1691 
1692 		/* remove SETUP packet from data */
1693 		sxfer->rem_len -= 8;
1694 		sxfer->curr_data += 8;
1695 		break;
1696 	default:
1697 		goto failure;
1698 	}
1699 
1700 	buffsize = libusb10_get_buffsize(pdev, uxfer);
1701 	maxframe = libusb10_get_maxframe(pdev, uxfer);
1702 
1703 	/* make sure the transfer is opened */
1704 	err = libusb20_tr_open_stream(pxfer0, buffsize, maxframe,
1705 	    endpoint, sxfer->stream_id);
1706 	if (err && (err != LIBUSB20_ERROR_BUSY)) {
1707 		goto failure;
1708 	}
1709 	libusb20_tr_start(pxfer0);
1710 	return;
1711 
1712 failure:
1713 	libusb10_complete_transfer(pxfer0, sxfer, LIBUSB_TRANSFER_ERROR);
1714 	/* make sure our event loop spins the done handler */
1715 	libusb_interrupt_event_handler(dev->ctx);
1716 }
1717 
1718 /* The following function must be called unlocked */
1719 
1720 int
1721 libusb_submit_transfer(struct libusb_transfer *uxfer)
1722 {
1723 	struct libusb20_transfer *pxfer0;
1724 	struct libusb20_transfer *pxfer1;
1725 	struct libusb_super_transfer *sxfer;
1726 	struct libusb_device *dev;
1727 	uint8_t endpoint;
1728 	int err, mps;
1729 
1730 	if (uxfer == NULL)
1731 		return (LIBUSB_ERROR_INVALID_PARAM);
1732 
1733 	if (uxfer->dev_handle == NULL)
1734 		return (LIBUSB_ERROR_INVALID_PARAM);
1735 
1736 	endpoint = uxfer->endpoint;
1737 
1738 	dev = libusb_get_device(uxfer->dev_handle);
1739 
1740 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_submit_transfer enter");
1741 
1742 	sxfer = (struct libusb_super_transfer *)(
1743 	    (uint8_t *)uxfer - sizeof(*sxfer));
1744 
1745 	CTX_LOCK(dev->ctx);
1746 
1747 	pxfer0 = libusb10_get_transfer(uxfer->dev_handle, endpoint, 0);
1748 	pxfer1 = libusb10_get_transfer(uxfer->dev_handle, endpoint, 1);
1749 	mps = libusb_get_max_packet_size(dev, endpoint);
1750 
1751 	/*
1752 	 * The ADD_ZERO_PACKET flag only has an effect on host-to-device
1753 	 * (OUT) transfers whose length is an exact multiple of the maximum
1754 	 * packet size. Clear it otherwise so the kernel is not asked to
1755 	 * terminate the transfer with a short packet, see
1756 	 * libusb10_bulk_intr_proxy().
1757 	 */
1758 	if ((uxfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1759 	    ((endpoint & LIBUSB_ENDPOINT_IN) || uxfer->length % mps != 0))
1760 		uxfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1761 
1762 	if (pxfer0 == NULL || pxfer1 == NULL) {
1763 		err = LIBUSB_ERROR_OTHER;
1764 	} else if ((sxfer->entry.tqe_prev != NULL) ||
1765 	    (libusb20_tr_get_priv_sc1(pxfer0) == sxfer) ||
1766 	    (libusb20_tr_get_priv_sc1(pxfer1) == sxfer)) {
1767 		err = LIBUSB_ERROR_BUSY;
1768 	} else if (dev->device_is_gone != 0) {
1769 		err = LIBUSB_ERROR_NO_DEVICE;
1770 	} else {
1771 
1772 		/* set pending state */
1773 		sxfer->state = LIBUSB_SUPER_XFER_ST_PEND;
1774 
1775 		/* insert transfer into transfer head list */
1776 		TAILQ_INSERT_TAIL(&dev->tr_head, sxfer, entry);
1777 
1778 		/* start work transfers */
1779 		libusb10_submit_transfer_sub(
1780 		    uxfer->dev_handle, endpoint);
1781 
1782 		err = 0;		/* success */
1783 	}
1784 
1785 	CTX_UNLOCK(dev->ctx);
1786 
1787 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_submit_transfer leave %d", err);
1788 
1789 	return (err);
1790 }
1791 
1792 /* Asynchronous transfer cancel */
1793 
1794 int
1795 libusb_cancel_transfer(struct libusb_transfer *uxfer)
1796 {
1797 	struct libusb20_transfer *pxfer0;
1798 	struct libusb20_transfer *pxfer1;
1799 	struct libusb_super_transfer *sxfer;
1800 	struct libusb_device *dev;
1801 	struct libusb_device_handle *devh;
1802 	uint8_t endpoint;
1803 	int retval;
1804 
1805 	if (uxfer == NULL)
1806 		return (LIBUSB_ERROR_INVALID_PARAM);
1807 
1808 	/* check if not initialised */
1809 	if ((devh = uxfer->dev_handle) == NULL)
1810 		return (LIBUSB_ERROR_NOT_FOUND);
1811 
1812 	endpoint = uxfer->endpoint;
1813 
1814 	dev = libusb_get_device(devh);
1815 
1816 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_cancel_transfer enter");
1817 
1818 	sxfer = (struct libusb_super_transfer *)(
1819 	    (uint8_t *)uxfer - sizeof(*sxfer));
1820 
1821 	retval = 0;
1822 
1823 	CTX_LOCK(dev->ctx);
1824 
1825 	pxfer0 = libusb10_get_transfer(devh, endpoint, 0);
1826 	pxfer1 = libusb10_get_transfer(devh, endpoint, 1);
1827 
1828 	if (sxfer->state != LIBUSB_SUPER_XFER_ST_PEND) {
1829 		/* only update the transfer status */
1830 		uxfer->status = LIBUSB_TRANSFER_CANCELLED;
1831 		retval = LIBUSB_ERROR_NOT_FOUND;
1832 	} else if (sxfer->entry.tqe_prev != NULL) {
1833 		/* we are lucky - transfer is on a queue */
1834 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1835 		sxfer->entry.tqe_prev = NULL;
1836 		libusb10_complete_transfer(NULL,
1837 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1838 		/* make sure our event loop spins the done handler */
1839 		libusb_interrupt_event_handler(dev->ctx);
1840 	} else if (pxfer0 == NULL || pxfer1 == NULL) {
1841 		/* not started */
1842 		retval = LIBUSB_ERROR_NOT_FOUND;
1843 	} else if (libusb20_tr_get_priv_sc1(pxfer0) == sxfer) {
1844 		libusb10_complete_transfer(pxfer0,
1845 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1846 		if (dev->device_is_gone != 0) {
1847 			/* clear transfer pointer */
1848 			libusb20_tr_set_priv_sc1(pxfer0, NULL);
1849 			/* make sure our event loop spins the done handler */
1850 			libusb_interrupt_event_handler(dev->ctx);
1851 		} else {
1852 			libusb20_tr_stop(pxfer0);
1853 			/* make sure the queue doesn't stall */
1854 			libusb10_submit_transfer_sub(devh, endpoint);
1855 		}
1856 	} else if (libusb20_tr_get_priv_sc1(pxfer1) == sxfer) {
1857 		libusb10_complete_transfer(pxfer1,
1858 		    sxfer, LIBUSB_TRANSFER_CANCELLED);
1859 		/* check if handle is still active */
1860 		if (dev->device_is_gone != 0) {
1861 			/* clear transfer pointer */
1862 			libusb20_tr_set_priv_sc1(pxfer1, NULL);
1863 			/* make sure our event loop spins the done handler */
1864 			libusb_interrupt_event_handler(dev->ctx);
1865 		} else {
1866 			libusb20_tr_stop(pxfer1);
1867 			/* make sure the queue doesn't stall */
1868 			libusb10_submit_transfer_sub(devh, endpoint);
1869 		}
1870 	} else {
1871 		/* not started */
1872 		retval = LIBUSB_ERROR_NOT_FOUND;
1873 	}
1874 
1875 	CTX_UNLOCK(dev->ctx);
1876 
1877 	DPRINTF(dev->ctx, LIBUSB_LOG_LEVEL_DEBUG, "libusb_cancel_transfer leave");
1878 
1879 	return (retval);
1880 }
1881 
1882 UNEXPORTED void
1883 libusb10_cancel_all_transfer(libusb_device *dev)
1884 {
1885 	struct libusb20_device *pdev = dev->os_priv;
1886 	unsigned x;
1887 
1888 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1889 		struct libusb20_transfer *xfer;
1890 
1891 		xfer = libusb20_tr_get_pointer(pdev, x);
1892 		if (xfer == NULL)
1893 			continue;
1894 		libusb20_tr_close(xfer);
1895 	}
1896 }
1897 
1898 UNEXPORTED void
1899 libusb10_cancel_all_transfer_locked(struct libusb20_device *pdev, struct libusb_device *dev)
1900 {
1901 	struct libusb_super_transfer *sxfer;
1902 	unsigned x;
1903 
1904 	for (x = 0; x != LIBUSB_NUM_SW_ENDPOINTS; x++) {
1905 		struct libusb20_transfer *xfer;
1906 
1907 		xfer = libusb20_tr_get_pointer(pdev, x);
1908 		if (xfer == NULL)
1909 			continue;
1910 		if (libusb20_tr_pending(xfer) == 0)
1911 			continue;
1912 		sxfer = libusb20_tr_get_priv_sc1(xfer);
1913 		if (sxfer == NULL)
1914 			continue;
1915 		/* complete pending transfer */
1916 		libusb10_complete_transfer(xfer, sxfer, LIBUSB_TRANSFER_CANCELLED);
1917 	}
1918 
1919 	while ((sxfer = TAILQ_FIRST(&dev->tr_head))) {
1920 		TAILQ_REMOVE(&dev->tr_head, sxfer, entry);
1921 
1922 		/* complete pending transfer */
1923 		libusb10_complete_transfer(NULL, sxfer, LIBUSB_TRANSFER_CANCELLED);
1924 	}
1925 }
1926 
1927 uint16_t
1928 libusb_cpu_to_le16(uint16_t x)
1929 {
1930 	return (htole16(x));
1931 }
1932 
1933 uint16_t
1934 libusb_le16_to_cpu(uint16_t x)
1935 {
1936 	return (le16toh(x));
1937 }
1938 
1939 const char *
1940 libusb_strerror(int code)
1941 {
1942 	int entry = -code;
1943 
1944 	if (code == LIBUSB_ERROR_OTHER)
1945 		entry = LIBUSB_ERROR_COUNT - 1;
1946 	/*
1947 	 * The libusb upstream considers all code out of range a
1948 	 * LIBUSB_ERROR_OTHER. In FreeBSD, it is a special unknown error. We
1949 	 * preserve the FreeBSD implementation as I think it make sense.
1950 	 */
1951 	if (entry < 0 || entry >= LIBUSB_ERROR_COUNT)
1952 		entry = LIBUSB_ERROR_COUNT;
1953 
1954 	/*
1955 	 * Fall back to English one as the translation may be unimplemented
1956 	 * when adding new error code.
1957 	 */
1958 	if (default_language_context->err_strs[entry] == NULL)
1959 		return (libusb_language_ctx[0].err_strs[entry]);
1960 
1961 	return (default_language_context->err_strs[entry]);
1962 }
1963 
1964 const char *
1965 libusb_error_name(int code)
1966 {
1967 	switch (code) {
1968 	case LIBUSB_SUCCESS:
1969 		return ("LIBUSB_SUCCESS");
1970 	case LIBUSB_ERROR_IO:
1971 		return ("LIBUSB_ERROR_IO");
1972 	case LIBUSB_ERROR_INVALID_PARAM:
1973 		return ("LIBUSB_ERROR_INVALID_PARAM");
1974 	case LIBUSB_ERROR_ACCESS:
1975 		return ("LIBUSB_ERROR_ACCESS");
1976 	case LIBUSB_ERROR_NO_DEVICE:
1977 		return ("LIBUSB_ERROR_NO_DEVICE");
1978 	case LIBUSB_ERROR_NOT_FOUND:
1979 		return ("LIBUSB_ERROR_NOT_FOUND");
1980 	case LIBUSB_ERROR_BUSY:
1981 		return ("LIBUSB_ERROR_BUSY");
1982 	case LIBUSB_ERROR_TIMEOUT:
1983 		return ("LIBUSB_ERROR_TIMEOUT");
1984 	case LIBUSB_ERROR_OVERFLOW:
1985 		return ("LIBUSB_ERROR_OVERFLOW");
1986 	case LIBUSB_ERROR_PIPE:
1987 		return ("LIBUSB_ERROR_PIPE");
1988 	case LIBUSB_ERROR_INTERRUPTED:
1989 		return ("LIBUSB_ERROR_INTERRUPTED");
1990 	case LIBUSB_ERROR_NO_MEM:
1991 		return ("LIBUSB_ERROR_NO_MEM");
1992 	case LIBUSB_ERROR_NOT_SUPPORTED:
1993 		return ("LIBUSB_ERROR_NOT_SUPPORTED");
1994 	case LIBUSB_ERROR_OTHER:
1995 		return ("LIBUSB_ERROR_OTHER");
1996 	default:
1997 		return ("LIBUSB_ERROR_UNKNOWN");
1998 	}
1999 }
2000 
2001 int
2002 libusb_has_capability(uint32_t capability)
2003 {
2004 
2005 	switch (capability) {
2006 	case LIBUSB_CAP_HAS_CAPABILITY:
2007 	case LIBUSB_CAP_HAS_HOTPLUG:
2008 	case LIBUSB_CAP_HAS_HID_ACCESS:
2009 	case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2010 		return (1);
2011 	default:
2012 		return (0);
2013 	}
2014 }
2015 
2016 void
2017 libusb_log_va_args(struct libusb_context *ctx, enum libusb_log_level level,
2018     const char *fmt, ...)
2019 {
2020 	static const char *log_prefix[5] = {
2021 		[LIBUSB_LOG_LEVEL_ERROR] = "LIBUSB_ERROR",
2022 		[LIBUSB_LOG_LEVEL_WARNING] = "LIBUSB_WARN",
2023 		[LIBUSB_LOG_LEVEL_INFO] = "LIBUSB_INFO",
2024 		[LIBUSB_LOG_LEVEL_DEBUG] = "LIBUSB_DEBUG",
2025 	};
2026 
2027 	char buffer[LIBUSB_LOG_BUFFER_SIZE];
2028 	char new_fmt[LIBUSB_LOG_BUFFER_SIZE];
2029 	va_list args;
2030 
2031 	ctx = GET_CONTEXT(ctx);
2032 
2033 	if (ctx->debug < level)
2034 		return;
2035 
2036 	va_start(args, fmt);
2037 
2038 	snprintf(new_fmt, sizeof(new_fmt), "%s: %s\n", log_prefix[level], fmt);
2039 	vsnprintf(buffer, sizeof(buffer), new_fmt, args);
2040 
2041 	if (ctx->log_cb != NULL)
2042 		ctx->log_cb(ctx, level, buffer);
2043 	else
2044 		fputs(buffer, stdout);
2045 
2046 	va_end(args);
2047 }
2048 
2049 /*
2050  * Upstream code actually recognizes the first two characters to identify a
2051  * language. We do so to provide API compatibility with setlocale.
2052  */
2053 int
2054 libusb_setlocale(const char *locale)
2055 {
2056 	size_t idx;
2057 	const char *lang;
2058 
2059 	if (locale == NULL || strlen(locale) < 2 ||
2060 	    (locale[2] != '\0' && strchr("-_.", locale[2]) == NULL))
2061 		return (LIBUSB_ERROR_INVALID_PARAM);
2062 
2063 	for (idx = 0; idx < nitems(libusb_language_ctx); ++idx) {
2064 		lang = libusb_language_ctx[idx].lang_name;
2065 		if (tolower(locale[0]) == lang[0] &&
2066 		    tolower(locale[1]) == lang[1]) {
2067 			default_language_context = &libusb_language_ctx[idx];
2068 			return (LIBUSB_SUCCESS);
2069 		}
2070 	}
2071 
2072 	return (LIBUSB_ERROR_INVALID_PARAM);
2073 }
2074 
2075 unsigned char *
2076 libusb_dev_mem_alloc(libusb_device_handle *devh)
2077 {
2078 	return (NULL);
2079 }
2080 
2081 int
2082 libusb_dev_mem_free(libusb_device_handle *devh, unsigned char *buffer,
2083     size_t size)
2084 {
2085 	return (LIBUSB_ERROR_NOT_SUPPORTED);
2086 }
2087 
2088 int
2089 libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev,
2090     libusb_device_handle **dev_handle)
2091 {
2092 	return (LIBUSB_ERROR_NOT_SUPPORTED);
2093 }
2094 
2095 int
2096 libusb_set_option(libusb_context *ctx, enum libusb_option option, ...)
2097 {
2098 	int err = LIBUSB_SUCCESS;
2099 	enum libusb_log_level level;
2100 	va_list args;
2101 	libusb_log_cb callback;
2102 
2103 	ctx = GET_CONTEXT(ctx);
2104 	va_start(args, option);
2105 
2106 	switch (option) {
2107 	case LIBUSB_OPTION_LOG_LEVEL:
2108 		level = va_arg(args, enum libusb_log_level);
2109 		if (level < LIBUSB_LOG_LEVEL_NONE ||
2110 		    level > LIBUSB_LOG_LEVEL_DEBUG) {
2111 			err = LIBUSB_ERROR_INVALID_PARAM;
2112 			goto end;
2113 		}
2114 		break;
2115 	case LIBUSB_OPTION_LOG_CB:
2116 		callback = va_arg(args, libusb_log_cb);
2117 		break;
2118 	default:
2119 		break;
2120 	}
2121 
2122 	if (option >= LIBUSB_OPTION_MAX) {
2123 		err = LIBUSB_ERROR_INVALID_PARAM;
2124 		goto end;
2125 	}
2126 
2127 	/*
2128 	 * When it is default context, the context will be accessed by multiple
2129 	 * instances of libusb_context that will later be taken as the default
2130 	 * value when new instances are created.
2131 	 */
2132 	if (ctx == usbi_default_context)
2133 		CTX_LOCK(ctx);
2134 
2135 	switch (option) {
2136 	case LIBUSB_OPTION_LOG_LEVEL:
2137 		if (ctx->debug_fixed)
2138 			break;
2139 		ctx->debug = level;
2140 		break;
2141 	case LIBUSB_OPTION_LOG_CB:
2142 		ctx->log_cb = callback;
2143 		break;
2144 	case LIBUSB_OPTION_NO_DEVICE_DISCOVERY:
2145 		ctx->no_discovery = true;
2146 		break;
2147 		/*
2148 		 * We don't handle USBDK as it is a windows
2149 		 * backend specified SDK
2150 		 */
2151 	case LIBUSB_OPTION_USE_USBDK:
2152 		break;
2153 	default:
2154 		err = LIBUSB_ERROR_INVALID_PARAM;
2155 		break;
2156 	}
2157 
2158 	if (ctx == usbi_default_context)
2159 		CTX_UNLOCK(ctx);
2160 
2161 end:
2162 	va_end(args);
2163 	return (err);
2164 }
2165 
2166 void
2167 libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb, int mode)
2168 {
2169 	if ((mode & LIBUSB_LOG_CB_GLOBAL) && usbi_default_context != NULL)
2170 		usbi_default_context->log_cb = cb;
2171 	if (mode & LIBUSB_LOG_CB_CONTEXT) {
2172 		ctx = GET_CONTEXT(ctx);
2173 		if (ctx != NULL)
2174 			ctx->log_cb = cb;
2175 	}
2176 }
2177