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