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