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