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