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