xref: /freebsd/lib/libusb/libusb01.c (revision 2ba1d4970a06a1660b46f6fd99351d154b295683)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008 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 /*
29  * This file contains the emulation layer for LibUSB v0.1 from sourceforge.
30  */
31 
32 #ifdef LIBUSB_GLOBAL_INCLUDE_FILE
33 #include LIBUSB_GLOBAL_INCLUDE_FILE
34 #else
35 #include <errno.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <time.h>
40 #include <sys/queue.h>
41 #endif
42 
43 #include "libusb20.h"
44 #include "libusb20_desc.h"
45 #include "libusb20_int.h"
46 #include "usb.h"
47 
48 /*
49  * The two following macros were taken from the original LibUSB v0.1
50  * for sake of compatibility:
51  */
52 #define	LIST_ADD(begin, ent)	   \
53   do {				   \
54     if (begin) {		   \
55       ent->next = begin;	   \
56       ent->next->prev = ent;	   \
57     } else {			   \
58       ent->next = NULL;		   \
59     }				   \
60     ent->prev = NULL;		   \
61     begin = ent;		   \
62   } while(0)
63 
64 #define	LIST_DEL(begin, ent)		 \
65   do {					 \
66     if (ent->prev) {			 \
67       ent->prev->next = ent->next;	 \
68     } else {				 \
69       begin = ent->next;		 \
70     }					 \
71     if (ent->next) {			 \
72       ent->next->prev = ent->prev;	 \
73     }					 \
74     ent->prev = NULL;			 \
75     ent->next = NULL;			 \
76   } while (0)
77 
78 struct usb_bus *usb_busses = NULL;
79 
80 static struct usb_bus usb_global_bus = {
81 	.dirname = {"/dev/usb"},
82 	.root_dev = NULL,
83 	.devices = NULL,
84 };
85 
86 static struct libusb20_backend *usb_backend = NULL;
87 
88 struct usb_parse_state {
89 
90 	struct {
91 		struct libusb20_endpoint *currep;
92 		struct libusb20_interface *currifc;
93 		struct libusb20_config *currcfg;
94 		struct libusb20_me_struct *currextra;
95 	}	a;
96 
97 	struct {
98 		struct usb_config_descriptor *currcfg;
99 		struct usb_interface_descriptor *currifc;
100 		struct usb_endpoint_descriptor *currep;
101 		struct usb_interface *currifcw;
102 		uint8_t *currextra;
103 	}	b;
104 
105 	uint8_t	preparse;
106 };
107 
108 static struct libusb20_transfer *
109 usb_get_transfer_by_ep_no(usb_dev_handle * dev, uint8_t ep_no)
110 {
111 	struct libusb20_device *pdev = (void *)dev;
112 	struct libusb20_transfer *xfer;
113 	int err;
114 	uint32_t bufsize;
115 	uint8_t x;
116 	uint8_t speed;
117 
118 	x = (ep_no & LIBUSB20_ENDPOINT_ADDRESS_MASK) * 2;
119 
120 	if (ep_no & LIBUSB20_ENDPOINT_DIR_MASK) {
121 		/* this is an IN endpoint */
122 		x |= 1;
123 	}
124 	speed = libusb20_dev_get_speed(pdev);
125 
126 	/* select a sensible buffer size */
127 	if (speed == LIBUSB20_SPEED_LOW) {
128 		bufsize = 256;
129 	} else if (speed == LIBUSB20_SPEED_FULL) {
130 		bufsize = 4096;
131 	} else if (speed == LIBUSB20_SPEED_SUPER) {
132 		bufsize = 65536;
133 	} else {
134 		bufsize = 16384;
135 	}
136 
137 	xfer = libusb20_tr_get_pointer(pdev, x);
138 
139 	if (xfer == NULL)
140 		return (xfer);
141 
142 	err = libusb20_tr_open(xfer, bufsize, 1, ep_no);
143 	if (err == LIBUSB20_ERROR_BUSY) {
144 		/* already opened */
145 		return (xfer);
146 	} else if (err) {
147 		return (NULL);
148 	}
149 	/* success */
150 	return (xfer);
151 }
152 
153 usb_dev_handle *
154 usb_open(struct usb_device *dev)
155 {
156 	int err;
157 
158 	err = libusb20_dev_open(dev->dev, 16 * 2);
159 	if (err == LIBUSB20_ERROR_BUSY) {
160 		/*
161 		 * Workaround buggy USB applications which open the USB
162 		 * device multiple times:
163 		 */
164 		return (dev->dev);
165 	}
166 	if (err)
167 		return (NULL);
168 
169 	/*
170 	 * Dequeue USB device from backend queue so that it does not get
171 	 * freed when the backend is re-scanned:
172 	 */
173 	libusb20_be_dequeue_device(usb_backend, dev->dev);
174 
175 	return (dev->dev);
176 }
177 
178 int
179 usb_close(usb_dev_handle * udev)
180 {
181 	struct usb_device *dev;
182 	int err;
183 
184 	err = libusb20_dev_close((void *)udev);
185 
186 	if (err)
187 		return (-1);
188 
189 	if (usb_backend != NULL) {
190 		/*
191 		 * Enqueue USB device to backend queue so that it gets freed
192 		 * when the backend is re-scanned:
193 		 */
194 		libusb20_be_enqueue_device(usb_backend, (void *)udev);
195 	} else {
196 		/*
197 		 * The backend is gone. Free device data so that we
198 		 * don't start leaking memory!
199 		 */
200 		dev = usb_device(udev);
201 		libusb20_dev_free((void *)udev);
202 		LIST_DEL(usb_global_bus.devices, dev);
203 		free(dev);
204 	}
205 	return (0);
206 }
207 
208 int
209 usb_get_string(usb_dev_handle * dev, int strindex,
210     int langid, char *buf, size_t buflen)
211 {
212 	int err;
213 
214 	if (dev == NULL)
215 		return (-1);
216 
217 	if (buflen > 65535)
218 		buflen = 65535;
219 
220 	err = libusb20_dev_req_string_sync((void *)dev,
221 	    strindex, langid, buf, buflen);
222 
223 	if (err)
224 		return (-1);
225 
226 	return (0);
227 }
228 
229 int
230 usb_get_string_simple(usb_dev_handle * dev, int strindex,
231     char *buf, size_t buflen)
232 {
233 	int err;
234 
235 	if (dev == NULL)
236 		return (-1);
237 
238 	if (buflen > 65535)
239 		buflen = 65535;
240 
241 	err = libusb20_dev_req_string_simple_sync((void *)dev,
242 	    strindex, buf, buflen);
243 
244 	if (err)
245 		return (-1);
246 
247 	return (strlen(buf));
248 }
249 
250 int
251 usb_get_descriptor_by_endpoint(usb_dev_handle * udev, int ep, uint8_t type,
252     uint8_t ep_index, void *buf, int size)
253 {
254 	memset(buf, 0, size);
255 
256 	if (udev == NULL)
257 		return (-1);
258 
259 	if (size > 65535)
260 		size = 65535;
261 
262 	return (usb_control_msg(udev, ep | USB_ENDPOINT_IN,
263 	    USB_REQ_GET_DESCRIPTOR, (type << 8) + ep_index, 0,
264 	    buf, size, 1000));
265 }
266 
267 int
268 usb_get_descriptor(usb_dev_handle * udev, uint8_t type, uint8_t desc_index,
269     void *buf, int size)
270 {
271 	memset(buf, 0, size);
272 
273 	if (udev == NULL)
274 		return (-1);
275 
276 	if (size > 65535)
277 		size = 65535;
278 
279 	return (usb_control_msg(udev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
280 	    (type << 8) + desc_index, 0, buf, size, 1000));
281 }
282 
283 int
284 usb_parse_descriptor(uint8_t *source, char *description, void *dest)
285 {
286 	uint8_t *sp = source;
287 	uint8_t *dp = dest;
288 	uint16_t w;
289 	uint32_t d;
290 	char *cp;
291 
292 	for (cp = description; *cp; cp++) {
293 		switch (*cp) {
294 		case 'b':		/* 8-bit byte */
295 			*dp++ = *sp++;
296 			break;
297 			/*
298 			 * 16-bit word, convert from little endian to CPU
299 			 */
300 		case 'w':
301 			w = (sp[1] << 8) | sp[0];
302 			sp += 2;
303 			/* Align to word boundary */
304 			dp += ((dp - (uint8_t *)0) & 1);
305 			*((uint16_t *)dp) = w;
306 			dp += 2;
307 			break;
308 			/*
309 			 * 32-bit dword, convert from little endian to CPU
310 			 */
311 		case 'd':
312 			d = (sp[3] << 24) | (sp[2] << 16) |
313 			    (sp[1] << 8) | sp[0];
314 			sp += 4;
315 			/* Align to word boundary */
316 			dp += ((dp - (uint8_t *)0) & 1);
317 			/* Align to double word boundary */
318 			dp += ((dp - (uint8_t *)0) & 2);
319 			*((uint32_t *)dp) = d;
320 			dp += 4;
321 			break;
322 		}
323 	}
324 	return (sp - source);
325 }
326 
327 static void
328 usb_parse_extra(struct usb_parse_state *ps, uint8_t **pptr, int *plen)
329 {
330 	void *ptr;
331 	uint16_t len;
332 
333 	ptr = ps->a.currextra->ptr;
334 	len = ps->a.currextra->len;
335 
336 	if (ps->preparse == 0) {
337 		memcpy(ps->b.currextra, ptr, len);
338 		*pptr = ps->b.currextra;
339 		*plen = len;
340 	}
341 	ps->b.currextra += len;
342 	return;
343 }
344 
345 static void
346 usb_parse_endpoint(struct usb_parse_state *ps)
347 {
348 	struct usb_endpoint_descriptor *bep;
349 	struct libusb20_endpoint *aep;
350 
351 	aep = ps->a.currep;
352 	bep = ps->b.currep++;
353 
354 	if (ps->preparse == 0) {
355 		/* copy descriptor fields */
356 		bep->bLength = aep->desc.bLength;
357 		bep->bDescriptorType = aep->desc.bDescriptorType;
358 		bep->bEndpointAddress = aep->desc.bEndpointAddress;
359 		bep->bmAttributes = aep->desc.bmAttributes;
360 		bep->wMaxPacketSize = aep->desc.wMaxPacketSize;
361 		bep->bInterval = aep->desc.bInterval;
362 		bep->bRefresh = aep->desc.bRefresh;
363 		bep->bSynchAddress = aep->desc.bSynchAddress;
364 	}
365 	ps->a.currextra = &aep->extra;
366 	usb_parse_extra(ps, &bep->extra, &bep->extralen);
367 	return;
368 }
369 
370 static void
371 usb_parse_iface_sub(struct usb_parse_state *ps)
372 {
373 	struct libusb20_interface *aifc;
374 	struct usb_interface_descriptor *bifc;
375 	uint8_t x;
376 
377 	aifc = ps->a.currifc;
378 	bifc = ps->b.currifc++;
379 
380 	if (ps->preparse == 0) {
381 		/* copy descriptor fields */
382 		bifc->bLength = aifc->desc.bLength;
383 		bifc->bDescriptorType = aifc->desc.bDescriptorType;
384 		bifc->bInterfaceNumber = aifc->desc.bInterfaceNumber;
385 		bifc->bAlternateSetting = aifc->desc.bAlternateSetting;
386 		bifc->bNumEndpoints = aifc->num_endpoints;
387 		bifc->bInterfaceClass = aifc->desc.bInterfaceClass;
388 		bifc->bInterfaceSubClass = aifc->desc.bInterfaceSubClass;
389 		bifc->bInterfaceProtocol = aifc->desc.bInterfaceProtocol;
390 		bifc->iInterface = aifc->desc.iInterface;
391 		bifc->endpoint = ps->b.currep;
392 	}
393 	for (x = 0; x != aifc->num_endpoints; x++) {
394 		ps->a.currep = aifc->endpoints + x;
395 		usb_parse_endpoint(ps);
396 	}
397 
398 	ps->a.currextra = &aifc->extra;
399 	usb_parse_extra(ps, &bifc->extra, &bifc->extralen);
400 	return;
401 }
402 
403 static void
404 usb_parse_iface(struct usb_parse_state *ps)
405 {
406 	struct libusb20_interface *aifc;
407 	struct usb_interface *bifc;
408 	uint8_t x;
409 
410 	aifc = ps->a.currifc;
411 	bifc = ps->b.currifcw++;
412 
413 	if (ps->preparse == 0) {
414 		/* initialise interface wrapper */
415 		bifc->altsetting = ps->b.currifc;
416 		bifc->num_altsetting = aifc->num_altsetting + 1;
417 	}
418 	usb_parse_iface_sub(ps);
419 
420 	for (x = 0; x != aifc->num_altsetting; x++) {
421 		ps->a.currifc = aifc->altsetting + x;
422 		usb_parse_iface_sub(ps);
423 	}
424 	return;
425 }
426 
427 static void
428 usb_parse_config(struct usb_parse_state *ps)
429 {
430 	struct libusb20_config *acfg;
431 	struct usb_config_descriptor *bcfg;
432 	uint8_t x;
433 
434 	acfg = ps->a.currcfg;
435 	bcfg = ps->b.currcfg;
436 
437 	if (ps->preparse == 0) {
438 		/* initialise config wrapper */
439 		bcfg->bLength = acfg->desc.bLength;
440 		bcfg->bDescriptorType = acfg->desc.bDescriptorType;
441 		bcfg->wTotalLength = acfg->desc.wTotalLength;
442 		bcfg->bNumInterfaces = acfg->num_interface;
443 		bcfg->bConfigurationValue = acfg->desc.bConfigurationValue;
444 		bcfg->iConfiguration = acfg->desc.iConfiguration;
445 		bcfg->bmAttributes = acfg->desc.bmAttributes;
446 		bcfg->MaxPower = acfg->desc.bMaxPower;
447 		bcfg->interface = ps->b.currifcw;
448 	}
449 	for (x = 0; x != acfg->num_interface; x++) {
450 		ps->a.currifc = acfg->interface + x;
451 		usb_parse_iface(ps);
452 	}
453 
454 	ps->a.currextra = &acfg->extra;
455 	usb_parse_extra(ps, &bcfg->extra, &bcfg->extralen);
456 	return;
457 }
458 
459 int
460 usb_parse_configuration(struct usb_config_descriptor *config,
461     uint8_t *buffer)
462 {
463 	struct usb_parse_state ps;
464 	uint8_t *ptr;
465 	uint32_t a;
466 	uint32_t b;
467 	uint32_t c;
468 	uint32_t d;
469 
470 	if ((buffer == NULL) || (config == NULL)) {
471 		return (-1);
472 	}
473 	memset(&ps, 0, sizeof(ps));
474 
475 	ps.a.currcfg = libusb20_parse_config_desc(buffer);
476 	ps.b.currcfg = config;
477 	if (ps.a.currcfg == NULL) {
478 		/* could not parse config or out of memory */
479 		return (-1);
480 	}
481 	/* do the pre-parse */
482 	ps.preparse = 1;
483 	usb_parse_config(&ps);
484 
485 	a = ((uint8_t *)(ps.b.currifcw) - ((uint8_t *)0));
486 	b = ((uint8_t *)(ps.b.currifc) - ((uint8_t *)0));
487 	c = ((uint8_t *)(ps.b.currep) - ((uint8_t *)0));
488 	d = ((uint8_t *)(ps.b.currextra) - ((uint8_t *)0));
489 
490 	/* allocate memory for our configuration */
491 	ptr = malloc(a + b + c + d);
492 	if (ptr == NULL) {
493 		/* free config structure */
494 		free(ps.a.currcfg);
495 		return (-1);
496 	}
497 
498 	/* "currifcw" must be first, hence this pointer is freed */
499 	ps.b.currifcw = (void *)(ptr);
500 	ps.b.currifc = (void *)(ptr + a);
501 	ps.b.currep = (void *)(ptr + a + b);
502 	ps.b.currextra = (void *)(ptr + a + b + c);
503 
504 	/* generate a libusb v0.1 compatible structure */
505 	ps.preparse = 0;
506 	usb_parse_config(&ps);
507 
508 	/* free config structure */
509 	free(ps.a.currcfg);
510 
511 	return (0);			/* success */
512 }
513 
514 void
515 usb_destroy_configuration(struct usb_device *dev)
516 {
517 	uint8_t c;
518 
519 	if (dev->config == NULL) {
520 		return;
521 	}
522 	for (c = 0; c != dev->descriptor.bNumConfigurations; c++) {
523 		struct usb_config_descriptor *cf = &dev->config[c];
524 
525 		if (cf->interface != NULL) {
526 			free(cf->interface);
527 			cf->interface = NULL;
528 		}
529 	}
530 
531 	free(dev->config);
532 	dev->config = NULL;
533 	return;
534 }
535 
536 void
537 usb_fetch_and_parse_descriptors(usb_dev_handle * udev)
538 {
539 	struct usb_device *dev;
540 	struct libusb20_device *pdev;
541 	uint8_t *ptr;
542 	int error;
543 	uint32_t size;
544 	uint16_t len;
545 	uint8_t x;
546 
547 	if (udev == NULL) {
548 		/* be NULL safe */
549 		return;
550 	}
551 	dev = usb_device(udev);
552 	pdev = (void *)udev;
553 
554 	if (dev->descriptor.bNumConfigurations == 0) {
555 		/* invalid device */
556 		return;
557 	}
558 	size = dev->descriptor.bNumConfigurations *
559 	    sizeof(struct usb_config_descriptor);
560 
561 	dev->config = malloc(size);
562 	if (dev->config == NULL) {
563 		/* out of memory */
564 		return;
565 	}
566 	memset(dev->config, 0, size);
567 
568 	for (x = 0; x != dev->descriptor.bNumConfigurations; x++) {
569 
570 		error = (pdev->methods->get_config_desc_full) (
571 		    pdev, &ptr, &len, x);
572 
573 		if (error) {
574 			usb_destroy_configuration(dev);
575 			return;
576 		}
577 		usb_parse_configuration(dev->config + x, ptr);
578 
579 		/* free config buffer */
580 		free(ptr);
581 	}
582 	return;
583 }
584 
585 static int
586 usb_std_io(usb_dev_handle * dev, int ep, char *bytes, int size,
587     int timeout, int is_intr)
588 {
589 	struct libusb20_transfer *xfer;
590 	uint32_t temp;
591 	uint32_t maxsize;
592 	uint32_t actlen;
593 	char *oldbytes;
594 
595 	xfer = usb_get_transfer_by_ep_no(dev, ep);
596 	if (xfer == NULL)
597 		return (-1);
598 
599 	if (libusb20_tr_pending(xfer)) {
600 		/* there is already a transfer ongoing */
601 		return (-1);
602 	}
603 	maxsize = libusb20_tr_get_max_total_length(xfer);
604 	oldbytes = bytes;
605 
606 	/*
607 	 * We allow transferring zero bytes which is the same
608 	 * equivalent to a zero length USB packet.
609 	 */
610 	do {
611 
612 		temp = size;
613 		if (temp > maxsize) {
614 			/* find maximum possible length */
615 			temp = maxsize;
616 		}
617 		if (is_intr)
618 			libusb20_tr_setup_intr(xfer, bytes, temp, timeout);
619 		else
620 			libusb20_tr_setup_bulk(xfer, bytes, temp, timeout);
621 
622 		libusb20_tr_start(xfer);
623 
624 		while (1) {
625 
626 			if (libusb20_dev_process((void *)dev) != 0) {
627 				/* device detached */
628 				return (-1);
629 			}
630 			if (libusb20_tr_pending(xfer) == 0) {
631 				/* transfer complete */
632 				break;
633 			}
634 			/* wait for USB event from kernel */
635 			libusb20_dev_wait_process((void *)dev, -1);
636 		}
637 
638 		switch (libusb20_tr_get_status(xfer)) {
639 		case 0:
640 			/* success */
641 			break;
642 		case LIBUSB20_TRANSFER_TIMED_OUT:
643 			/* transfer timeout */
644 			return (-ETIMEDOUT);
645 		default:
646 			/* other transfer error */
647 			return (-ENXIO);
648 		}
649 		actlen = libusb20_tr_get_actual_length(xfer);
650 
651 		bytes += actlen;
652 		size -= actlen;
653 
654 		if (actlen != temp) {
655 			/* short transfer */
656 			break;
657 		}
658 	} while (size > 0);
659 
660 	return (bytes - oldbytes);
661 }
662 
663 int
664 usb_bulk_write(usb_dev_handle * dev, int ep, char *bytes,
665     int size, int timeout)
666 {
667 	return (usb_std_io(dev, ep & ~USB_ENDPOINT_DIR_MASK,
668 	    bytes, size, timeout, 0));
669 }
670 
671 int
672 usb_bulk_read(usb_dev_handle * dev, int ep, char *bytes,
673     int size, int timeout)
674 {
675 	return (usb_std_io(dev, ep | USB_ENDPOINT_DIR_MASK,
676 	    bytes, size, timeout, 0));
677 }
678 
679 int
680 usb_interrupt_write(usb_dev_handle * dev, int ep, char *bytes,
681     int size, int timeout)
682 {
683 	return (usb_std_io(dev, ep & ~USB_ENDPOINT_DIR_MASK,
684 	    bytes, size, timeout, 1));
685 }
686 
687 int
688 usb_interrupt_read(usb_dev_handle * dev, int ep, char *bytes,
689     int size, int timeout)
690 {
691 	return (usb_std_io(dev, ep | USB_ENDPOINT_DIR_MASK,
692 	    bytes, size, timeout, 1));
693 }
694 
695 int
696 usb_control_msg(usb_dev_handle * dev, int requesttype, int request,
697     int value, int wIndex, char *bytes, int size, int timeout)
698 {
699 	struct LIBUSB20_CONTROL_SETUP_DECODED req;
700 	int err;
701 	uint16_t actlen;
702 
703 	LIBUSB20_INIT(LIBUSB20_CONTROL_SETUP, &req);
704 
705 	req.bmRequestType = requesttype;
706 	req.bRequest = request;
707 	req.wValue = value;
708 	req.wIndex = wIndex;
709 	req.wLength = size;
710 
711 	err = libusb20_dev_request_sync((void *)dev, &req, bytes,
712 	    &actlen, timeout, 0);
713 
714 	if (err)
715 		return (-1);
716 
717 	return (actlen);
718 }
719 
720 int
721 usb_set_configuration(usb_dev_handle * udev, int bConfigurationValue)
722 {
723 	struct usb_device *dev;
724 	int err;
725 	uint8_t i;
726 
727 	/*
728 	 * Need to translate from "bConfigurationValue" to
729 	 * configuration index:
730 	 */
731 
732 	if (bConfigurationValue == 0) {
733 		/* unconfigure */
734 		i = 255;
735 	} else {
736 		/* lookup configuration index */
737 		dev = usb_device(udev);
738 
739 		/* check if the configuration array is not there */
740 		if (dev->config == NULL) {
741 			return (-1);
742 		}
743 		for (i = 0;; i++) {
744 			if (i == dev->descriptor.bNumConfigurations) {
745 				/* "bConfigurationValue" not found */
746 				return (-1);
747 			}
748 			if ((dev->config + i)->bConfigurationValue ==
749 			    bConfigurationValue) {
750 				break;
751 			}
752 		}
753 	}
754 
755 	err = libusb20_dev_set_config_index((void *)udev, i);
756 
757 	if (err)
758 		return (-1);
759 
760 	return (0);
761 }
762 
763 int
764 usb_claim_interface(usb_dev_handle * dev, int interface)
765 {
766 	struct libusb20_device *pdev = (void *)dev;
767 
768 	pdev->claimed_interface = interface;
769 
770 	return (0);
771 }
772 
773 int
774 usb_release_interface(usb_dev_handle * dev, int interface)
775 {
776 	/* do nothing */
777 	return (0);
778 }
779 
780 int
781 usb_set_altinterface(usb_dev_handle * dev, int alternate)
782 {
783 	struct libusb20_device *pdev = (void *)dev;
784 	int err;
785 	uint8_t iface;
786 
787 	iface = pdev->claimed_interface;
788 
789 	err = libusb20_dev_set_alt_index((void *)dev, iface, alternate);
790 
791 	if (err)
792 		return (-1);
793 
794 	return (0);
795 }
796 
797 int
798 usb_resetep(usb_dev_handle * dev, unsigned int ep)
799 {
800 	/* emulate an endpoint reset through clear-STALL */
801 	return (usb_clear_halt(dev, ep));
802 }
803 
804 int
805 usb_clear_halt(usb_dev_handle * dev, unsigned int ep)
806 {
807 	struct libusb20_transfer *xfer;
808 
809 	xfer = usb_get_transfer_by_ep_no(dev, ep);
810 	if (xfer == NULL)
811 		return (-1);
812 
813 	libusb20_tr_clear_stall_sync(xfer);
814 
815 	return (0);
816 }
817 
818 int
819 usb_reset(usb_dev_handle * dev)
820 {
821 	int err;
822 
823 	err = libusb20_dev_reset((void *)dev);
824 
825 	if (err)
826 		return (-1);
827 
828 	/*
829 	 * Be compatible with LibUSB from sourceforge and close the
830 	 * handle after reset!
831 	 */
832 	return (usb_close(dev));
833 }
834 
835 int
836 usb_check_connected(usb_dev_handle * dev)
837 {
838 	int err;
839 
840 	err = libusb20_dev_check_connected((void *)dev);
841 
842 	if (err)
843 		return (-1);
844 
845 	return (0);
846 }
847 
848 const char *
849 usb_strerror(void)
850 {
851 	/* TODO */
852 	return ("Unknown error");
853 }
854 
855 void
856 usb_init(void)
857 {
858 	/* nothing to do */
859 	return;
860 }
861 
862 void
863 usb_set_debug(int level)
864 {
865 	/* use kernel UGEN debugging if you need to see what is going on */
866 	return;
867 }
868 
869 int
870 usb_find_busses(void)
871 {
872 	usb_busses = &usb_global_bus;
873 	return (1);
874 }
875 
876 int
877 usb_find_devices(void)
878 {
879 	struct libusb20_device *pdev;
880 	struct usb_device *udev;
881 	struct LIBUSB20_DEVICE_DESC_DECODED *ddesc;
882 	int devnum;
883 	int err;
884 
885 	/* cleanup after last device search */
886 	/* close all opened devices, if any */
887 
888 	while ((pdev = libusb20_be_device_foreach(usb_backend, NULL))) {
889 		udev = pdev->privLuData;
890 		libusb20_be_dequeue_device(usb_backend, pdev);
891 		libusb20_dev_free(pdev);
892 		if (udev != NULL) {
893 			LIST_DEL(usb_global_bus.devices, udev);
894 			free(udev);
895 		}
896 	}
897 
898 	/* free old USB backend, if any */
899 
900 	libusb20_be_free(usb_backend);
901 
902 	/* do a new backend device search */
903 	usb_backend = libusb20_be_alloc_default();
904 	if (usb_backend == NULL) {
905 		return (-1);
906 	}
907 	/* iterate all devices */
908 
909 	devnum = 1;
910 	pdev = NULL;
911 	while ((pdev = libusb20_be_device_foreach(usb_backend, pdev))) {
912 		udev = malloc(sizeof(*udev));
913 		if (udev == NULL)
914 			break;
915 
916 		memset(udev, 0, sizeof(*udev));
917 
918 		udev->bus = &usb_global_bus;
919 
920 		snprintf(udev->filename, sizeof(udev->filename),
921 		    "/dev/ugen%u.%u",
922 		    libusb20_dev_get_bus_number(pdev),
923 		    libusb20_dev_get_address(pdev));
924 
925 		ddesc = libusb20_dev_get_device_desc(pdev);
926 
927 		udev->descriptor.bLength = sizeof(udev->descriptor);
928 		udev->descriptor.bDescriptorType = ddesc->bDescriptorType;
929 		udev->descriptor.bcdUSB = ddesc->bcdUSB;
930 		udev->descriptor.bDeviceClass = ddesc->bDeviceClass;
931 		udev->descriptor.bDeviceSubClass = ddesc->bDeviceSubClass;
932 		udev->descriptor.bDeviceProtocol = ddesc->bDeviceProtocol;
933 		udev->descriptor.bMaxPacketSize0 = ddesc->bMaxPacketSize0;
934 		udev->descriptor.idVendor = ddesc->idVendor;
935 		udev->descriptor.idProduct = ddesc->idProduct;
936 		udev->descriptor.bcdDevice = ddesc->bcdDevice;
937 		udev->descriptor.iManufacturer = ddesc->iManufacturer;
938 		udev->descriptor.iProduct = ddesc->iProduct;
939 		udev->descriptor.iSerialNumber = ddesc->iSerialNumber;
940 		udev->descriptor.bNumConfigurations =
941 		    ddesc->bNumConfigurations;
942 		if (udev->descriptor.bNumConfigurations > USB_MAXCONFIG) {
943 			/* truncate number of configurations */
944 			udev->descriptor.bNumConfigurations = USB_MAXCONFIG;
945 		}
946 		udev->devnum = devnum++;
947 		/* link together the two structures */
948 		udev->dev = pdev;
949 		pdev->privLuData = udev;
950 
951 		err = libusb20_dev_open(pdev, 0);
952 		if (err == 0) {
953 			/* XXX get all config descriptors by default */
954 			usb_fetch_and_parse_descriptors((void *)pdev);
955 			libusb20_dev_close(pdev);
956 		}
957 		LIST_ADD(usb_global_bus.devices, udev);
958 	}
959 
960 	return (devnum - 1);			/* success */
961 }
962 
963 struct usb_device *
964 usb_device(usb_dev_handle * dev)
965 {
966 	struct libusb20_device *pdev;
967 
968 	pdev = (void *)dev;
969 
970 	return (pdev->privLuData);
971 }
972 
973 struct usb_bus *
974 usb_get_busses(void)
975 {
976 	return (usb_busses);
977 }
978 
979 int
980 usb_get_driver_np(usb_dev_handle * dev, int interface, char *name, int namelen)
981 {
982 	struct libusb20_device *pdev;
983 	char *ptr;
984 	int err;
985 
986 	pdev = (void *)dev;
987 
988 	if (pdev == NULL)
989 		return (-1);
990 	if (namelen < 1)
991 		return (-1);
992 	if (namelen > 255)
993 		namelen = 255;
994 
995 	err = libusb20_dev_get_iface_desc(pdev, interface, name, namelen);
996 	if (err != 0)
997 		return (-1);
998 
999 	/* we only want the driver name */
1000 	ptr = strstr(name, ":");
1001 	if (ptr != NULL)
1002 		*ptr = 0;
1003 
1004 	return (0);
1005 }
1006 
1007 int
1008 usb_detach_kernel_driver_np(usb_dev_handle * dev, int interface)
1009 {
1010 	struct libusb20_device *pdev;
1011 	int err;
1012 
1013 	pdev = (void *)dev;
1014 
1015 	if (pdev == NULL)
1016 		return (-1);
1017 
1018 	err = libusb20_dev_detach_kernel_driver(pdev, interface);
1019 	if (err != 0)
1020 		return (-1);
1021 
1022 	return (0);
1023 }
1024