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