xref: /freebsd/lib/libusb/libusb20.c (revision 911f0260390e18cf85f3dbf2c719b593efdc1e3c)
1 /* $FreeBSD$ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause
4  *
5  * Copyright (c) 2008-2009 Hans Petter Selasky. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #ifdef LIBUSB_GLOBAL_INCLUDE_FILE
30 #include LIBUSB_GLOBAL_INCLUDE_FILE
31 #else
32 #include <ctype.h>
33 #include <poll.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <time.h>
38 #include <sys/queue.h>
39 #endif
40 
41 #include "libusb20.h"
42 #include "libusb20_desc.h"
43 #include "libusb20_int.h"
44 
45 static int
46 dummy_int(void)
47 {
48 	return (LIBUSB20_ERROR_NOT_SUPPORTED);
49 }
50 
51 static void
52 dummy_void(void)
53 {
54 	return;
55 }
56 
57 static void
58 dummy_callback(struct libusb20_transfer *xfer)
59 {
60 	;				/* style fix */
61 	switch (libusb20_tr_get_status(xfer)) {
62 	case LIBUSB20_TRANSFER_START:
63 		libusb20_tr_submit(xfer);
64 		break;
65 	default:
66 		/* complete or error */
67 		break;
68 	}
69 	return;
70 }
71 
72 #define	dummy_get_config_desc_full (void *)dummy_int
73 #define	dummy_get_config_index (void *)dummy_int
74 #define	dummy_set_config_index (void *)dummy_int
75 #define	dummy_set_alt_index (void *)dummy_int
76 #define	dummy_reset_device (void *)dummy_int
77 #define	dummy_check_connected (void *)dummy_int
78 #define	dummy_set_power_mode (void *)dummy_int
79 #define	dummy_get_power_mode (void *)dummy_int
80 #define	dummy_get_power_usage (void *)dummy_int
81 #define	dummy_get_stats (void *)dummy_int
82 #define	dummy_kernel_driver_active (void *)dummy_int
83 #define	dummy_detach_kernel_driver (void *)dummy_int
84 #define	dummy_do_request_sync (void *)dummy_int
85 #define	dummy_tr_open (void *)dummy_int
86 #define	dummy_tr_close (void *)dummy_int
87 #define	dummy_tr_clear_stall_sync (void *)dummy_int
88 #define	dummy_process (void *)dummy_int
89 #define	dummy_dev_info (void *)dummy_int
90 #define	dummy_dev_get_iface_driver (void *)dummy_int
91 
92 #define	dummy_tr_submit (void *)dummy_void
93 #define	dummy_tr_cancel_async (void *)dummy_void
94 
95 static const struct libusb20_device_methods libusb20_dummy_methods = {
96 	LIBUSB20_DEVICE(LIBUSB20_DECLARE, dummy)
97 };
98 
99 void
100 libusb20_tr_callback_wrapper(struct libusb20_transfer *xfer)
101 {
102 	;				/* style fix */
103 
104 repeat:
105 
106 	if (!xfer->is_pending) {
107 		xfer->status = LIBUSB20_TRANSFER_START;
108 	} else {
109 		xfer->is_pending = 0;
110 	}
111 
112 	xfer->callback(xfer);
113 
114 	if (xfer->is_restart) {
115 		xfer->is_restart = 0;
116 		goto repeat;
117 	}
118 	if (xfer->is_draining &&
119 	    (!xfer->is_pending)) {
120 		xfer->is_draining = 0;
121 		xfer->status = LIBUSB20_TRANSFER_DRAINED;
122 		xfer->callback(xfer);
123 	}
124 	return;
125 }
126 
127 int
128 libusb20_tr_close(struct libusb20_transfer *xfer)
129 {
130 	int error;
131 
132 	if (!xfer->is_opened) {
133 		return (LIBUSB20_ERROR_OTHER);
134 	}
135 	error = xfer->pdev->methods->tr_close(xfer);
136 
137 	if (xfer->pLength) {
138 		free(xfer->pLength);
139 	}
140 	if (xfer->ppBuffer) {
141 		free(xfer->ppBuffer);
142 	}
143 	/* reset variable fields in case the transfer is opened again */
144 	xfer->priv_sc0 = NULL;
145 	xfer->priv_sc1 = NULL;
146 	xfer->is_opened = 0;
147 	xfer->is_pending = 0;
148 	xfer->is_cancel = 0;
149 	xfer->is_draining = 0;
150 	xfer->is_restart = 0;
151 	xfer->status = 0;
152 	xfer->flags = 0;
153 	xfer->nFrames = 0;
154 	xfer->aFrames = 0;
155 	xfer->timeout = 0;
156 	xfer->maxFrames = 0;
157 	xfer->maxTotalLength = 0;
158 	xfer->maxPacketLen = 0;
159 	return (error);
160 }
161 
162 int
163 libusb20_tr_open(struct libusb20_transfer *xfer, uint32_t MaxBufSize,
164     uint32_t MaxFrameCount, uint8_t ep_no)
165 {
166 	return (libusb20_tr_open_stream(xfer, MaxBufSize, MaxFrameCount, ep_no, 0));
167 }
168 
169 int
170 libusb20_tr_open_stream(struct libusb20_transfer *xfer, uint32_t MaxBufSize,
171     uint32_t MaxFrameCount, uint8_t ep_no, uint16_t stream_id)
172 {
173 	uint32_t size;
174 	uint8_t pre_scale;
175 	int error;
176 
177 	if (xfer->is_opened)
178 		return (LIBUSB20_ERROR_BUSY);
179 	if (MaxFrameCount & LIBUSB20_MAX_FRAME_PRE_SCALE) {
180 		MaxFrameCount &= ~LIBUSB20_MAX_FRAME_PRE_SCALE;
181 		/*
182 		 * The kernel can setup 8 times more frames when
183 		 * pre-scaling ISOCHRONOUS transfers. Make sure the
184 		 * length and pointer buffers are big enough:
185 		 */
186 		MaxFrameCount *= 8;
187 		pre_scale = 1;
188 	} else {
189 		pre_scale = 0;
190 	}
191 	if (MaxFrameCount == 0)
192 		return (LIBUSB20_ERROR_INVALID_PARAM);
193 
194 	xfer->maxFrames = MaxFrameCount;
195 
196 	size = MaxFrameCount * sizeof(xfer->pLength[0]);
197 	xfer->pLength = malloc(size);
198 	if (xfer->pLength == NULL) {
199 		return (LIBUSB20_ERROR_NO_MEM);
200 	}
201 	memset(xfer->pLength, 0, size);
202 
203 	size = MaxFrameCount * sizeof(xfer->ppBuffer[0]);
204 	xfer->ppBuffer = malloc(size);
205 	if (xfer->ppBuffer == NULL) {
206 		free(xfer->pLength);
207 		return (LIBUSB20_ERROR_NO_MEM);
208 	}
209 	memset(xfer->ppBuffer, 0, size);
210 
211 	if (pre_scale) {
212 		error = xfer->pdev->methods->tr_open(xfer, MaxBufSize,
213 		    MaxFrameCount / 8, ep_no, stream_id, 1);
214 	} else {
215 		error = xfer->pdev->methods->tr_open(xfer, MaxBufSize,
216 		    MaxFrameCount, ep_no, stream_id, 0);
217 	}
218 
219 	if (error) {
220 		free(xfer->ppBuffer);
221 		free(xfer->pLength);
222 	} else {
223 		xfer->is_opened = 1;
224 	}
225 	return (error);
226 }
227 
228 struct libusb20_transfer *
229 libusb20_tr_get_pointer(struct libusb20_device *pdev, uint16_t trIndex)
230 {
231 	if (trIndex >= pdev->nTransfer) {
232 		return (NULL);
233 	}
234 	return (pdev->pTransfer + trIndex);
235 }
236 
237 uint32_t
238 libusb20_tr_get_actual_frames(struct libusb20_transfer *xfer)
239 {
240 	return (xfer->aFrames);
241 }
242 
243 uint16_t
244 libusb20_tr_get_time_complete(struct libusb20_transfer *xfer)
245 {
246 	return (xfer->timeComplete);
247 }
248 
249 uint32_t
250 libusb20_tr_get_actual_length(struct libusb20_transfer *xfer)
251 {
252 	uint32_t x;
253 	uint32_t actlen = 0;
254 
255 	for (x = 0; x != xfer->aFrames; x++) {
256 		actlen += xfer->pLength[x];
257 	}
258 	return (actlen);
259 }
260 
261 uint32_t
262 libusb20_tr_get_max_frames(struct libusb20_transfer *xfer)
263 {
264 	return (xfer->maxFrames);
265 }
266 
267 uint32_t
268 libusb20_tr_get_max_packet_length(struct libusb20_transfer *xfer)
269 {
270 	/*
271 	 * Special Case NOTE: If the packet multiplier is non-zero for
272 	 * High Speed USB, the value returned is equal to
273 	 * "wMaxPacketSize * multiplier" !
274 	 */
275 	return (xfer->maxPacketLen);
276 }
277 
278 uint32_t
279 libusb20_tr_get_max_total_length(struct libusb20_transfer *xfer)
280 {
281 	return (xfer->maxTotalLength);
282 }
283 
284 uint8_t
285 libusb20_tr_get_status(struct libusb20_transfer *xfer)
286 {
287 	return (xfer->status);
288 }
289 
290 uint8_t
291 libusb20_tr_pending(struct libusb20_transfer *xfer)
292 {
293 	return (xfer->is_pending);
294 }
295 
296 void   *
297 libusb20_tr_get_priv_sc0(struct libusb20_transfer *xfer)
298 {
299 	return (xfer->priv_sc0);
300 }
301 
302 void   *
303 libusb20_tr_get_priv_sc1(struct libusb20_transfer *xfer)
304 {
305 	return (xfer->priv_sc1);
306 }
307 
308 void
309 libusb20_tr_stop(struct libusb20_transfer *xfer)
310 {
311 	if (!xfer->is_opened) {
312 		/* transfer is not opened */
313 		return;
314 	}
315 	if (!xfer->is_pending) {
316 		/* transfer not pending */
317 		return;
318 	}
319 	if (xfer->is_cancel) {
320 		/* already cancelling */
321 		return;
322 	}
323 	xfer->is_cancel = 1;		/* we are cancelling */
324 
325 	xfer->pdev->methods->tr_cancel_async(xfer);
326 	return;
327 }
328 
329 void
330 libusb20_tr_drain(struct libusb20_transfer *xfer)
331 {
332 	if (!xfer->is_opened) {
333 		/* transfer is not opened */
334 		return;
335 	}
336 	/* make sure that we are cancelling */
337 	libusb20_tr_stop(xfer);
338 
339 	if (xfer->is_pending) {
340 		xfer->is_draining = 1;
341 	}
342 	return;
343 }
344 
345 void
346 libusb20_tr_clear_stall_sync(struct libusb20_transfer *xfer)
347 {
348 	xfer->pdev->methods->tr_clear_stall_sync(xfer);
349 	return;
350 }
351 
352 void
353 libusb20_tr_set_buffer(struct libusb20_transfer *xfer, void *buffer, uint16_t frIndex)
354 {
355 	xfer->ppBuffer[frIndex] = buffer;
356 	return;
357 }
358 
359 void
360 libusb20_tr_set_callback(struct libusb20_transfer *xfer, libusb20_tr_callback_t *cb)
361 {
362 	xfer->callback = cb;
363 	return;
364 }
365 
366 void
367 libusb20_tr_set_flags(struct libusb20_transfer *xfer, uint8_t flags)
368 {
369 	xfer->flags = flags;
370 	return;
371 }
372 
373 uint32_t
374 libusb20_tr_get_length(struct libusb20_transfer *xfer, uint16_t frIndex)
375 {
376 	return (xfer->pLength[frIndex]);
377 }
378 
379 void
380 libusb20_tr_set_length(struct libusb20_transfer *xfer, uint32_t length, uint16_t frIndex)
381 {
382 	xfer->pLength[frIndex] = length;
383 	return;
384 }
385 
386 void
387 libusb20_tr_set_priv_sc0(struct libusb20_transfer *xfer, void *sc0)
388 {
389 	xfer->priv_sc0 = sc0;
390 	return;
391 }
392 
393 void
394 libusb20_tr_set_priv_sc1(struct libusb20_transfer *xfer, void *sc1)
395 {
396 	xfer->priv_sc1 = sc1;
397 	return;
398 }
399 
400 void
401 libusb20_tr_set_timeout(struct libusb20_transfer *xfer, uint32_t timeout)
402 {
403 	xfer->timeout = timeout;
404 	return;
405 }
406 
407 void
408 libusb20_tr_set_total_frames(struct libusb20_transfer *xfer, uint32_t nFrames)
409 {
410 	if (nFrames > xfer->maxFrames) {
411 		/* should not happen */
412 		nFrames = xfer->maxFrames;
413 	}
414 	xfer->nFrames = nFrames;
415 	return;
416 }
417 
418 void
419 libusb20_tr_setup_bulk(struct libusb20_transfer *xfer, void *pBuf, uint32_t length, uint32_t timeout)
420 {
421 	xfer->ppBuffer[0] = pBuf;
422 	xfer->pLength[0] = length;
423 	xfer->timeout = timeout;
424 	xfer->nFrames = 1;
425 	return;
426 }
427 
428 void
429 libusb20_tr_setup_control(struct libusb20_transfer *xfer, void *psetup, void *pBuf, uint32_t timeout)
430 {
431 	uint16_t len;
432 
433 	xfer->ppBuffer[0] = psetup;
434 	xfer->pLength[0] = 8;		/* fixed */
435 	xfer->timeout = timeout;
436 
437 	len = ((uint8_t *)psetup)[6] | (((uint8_t *)psetup)[7] << 8);
438 
439 	if (len != 0) {
440 		xfer->nFrames = 2;
441 		xfer->ppBuffer[1] = pBuf;
442 		xfer->pLength[1] = len;
443 	} else {
444 		xfer->nFrames = 1;
445 	}
446 	return;
447 }
448 
449 void
450 libusb20_tr_setup_intr(struct libusb20_transfer *xfer, void *pBuf, uint32_t length, uint32_t timeout)
451 {
452 	xfer->ppBuffer[0] = pBuf;
453 	xfer->pLength[0] = length;
454 	xfer->timeout = timeout;
455 	xfer->nFrames = 1;
456 	return;
457 }
458 
459 void
460 libusb20_tr_setup_isoc(struct libusb20_transfer *xfer, void *pBuf, uint32_t length, uint16_t frIndex)
461 {
462 	if (frIndex >= xfer->maxFrames) {
463 		/* should not happen */
464 		return;
465 	}
466 	xfer->ppBuffer[frIndex] = pBuf;
467 	xfer->pLength[frIndex] = length;
468 	return;
469 }
470 
471 uint8_t
472 libusb20_tr_bulk_intr_sync(struct libusb20_transfer *xfer,
473     void *pbuf, uint32_t length, uint32_t *pactlen,
474     uint32_t timeout)
475 {
476 	struct libusb20_device *pdev = xfer->pdev;
477 	uint32_t transfer_max;
478 	uint32_t transfer_act;
479 	uint8_t retval;
480 
481 	/* set some sensible default value */
482 	if (pactlen != NULL)
483 		*pactlen = 0;
484 
485 	/* check for error condition */
486 	if (libusb20_tr_pending(xfer))
487 		return (LIBUSB20_ERROR_OTHER);
488 
489 	do {
490 		/* compute maximum transfer length */
491 		transfer_max =
492 		    libusb20_tr_get_max_total_length(xfer);
493 
494 		if (transfer_max > length)
495 			transfer_max = length;
496 
497 		/* setup bulk or interrupt transfer */
498 		libusb20_tr_setup_bulk(xfer, pbuf,
499 		    transfer_max, timeout);
500 
501 		/* start the transfer */
502 		libusb20_tr_start(xfer);
503 
504 		/* wait for transfer completion */
505 		while (libusb20_dev_process(pdev) == 0) {
506 
507 			if (libusb20_tr_pending(xfer) == 0)
508 				break;
509 
510 			libusb20_dev_wait_process(pdev, -1);
511 		}
512 
513 		transfer_act = libusb20_tr_get_actual_length(xfer);
514 
515 		/* update actual length, if any */
516 		if (pactlen != NULL)
517 			pactlen[0] += transfer_act;
518 
519 		/* check transfer status */
520 		retval = libusb20_tr_get_status(xfer);
521 		if (retval)
522 			break;
523 
524 		/* check for short transfer */
525 		if (transfer_act != transfer_max)
526 			break;
527 
528 		/* update buffer pointer and length */
529 		pbuf = ((uint8_t *)pbuf) + transfer_max;
530 		length = length - transfer_max;
531 
532 	} while (length != 0);
533 
534 	return (retval);
535 }
536 
537 void
538 libusb20_tr_submit(struct libusb20_transfer *xfer)
539 {
540 	if (!xfer->is_opened) {
541 		/* transfer is not opened */
542 		return;
543 	}
544 	if (xfer->is_pending) {
545 		/* should not happen */
546 		return;
547 	}
548 	xfer->is_pending = 1;		/* we are pending */
549 	xfer->is_cancel = 0;		/* not cancelling */
550 	xfer->is_restart = 0;		/* not restarting */
551 
552 	xfer->pdev->methods->tr_submit(xfer);
553 	return;
554 }
555 
556 void
557 libusb20_tr_start(struct libusb20_transfer *xfer)
558 {
559 	if (!xfer->is_opened) {
560 		/* transfer is not opened */
561 		return;
562 	}
563 	if (xfer->is_pending) {
564 		if (xfer->is_cancel) {
565 			/* cancelling - restart */
566 			xfer->is_restart = 1;
567 		}
568 		/* transfer not pending */
569 		return;
570 	}
571 	/* get into the callback */
572 	libusb20_tr_callback_wrapper(xfer);
573 	return;
574 }
575 
576 /* USB device operations */
577 
578 int
579 libusb20_dev_close(struct libusb20_device *pdev)
580 {
581 	struct libusb20_transfer *xfer;
582 	uint16_t x;
583 	int error = 0;
584 
585 	if (!pdev->is_opened) {
586 		return (LIBUSB20_ERROR_OTHER);
587 	}
588 	for (x = 0; x != pdev->nTransfer; x++) {
589 		xfer = pdev->pTransfer + x;
590 
591 		if (!xfer->is_opened) {
592 			/* transfer is not opened */
593 			continue;
594 		}
595 
596 		libusb20_tr_drain(xfer);
597 
598 		libusb20_tr_close(xfer);
599 	}
600 
601 	if (pdev->pTransfer != NULL) {
602 		free(pdev->pTransfer);
603 		pdev->pTransfer = NULL;
604 	}
605 	error = pdev->beMethods->close_device(pdev);
606 
607 	pdev->methods = &libusb20_dummy_methods;
608 
609 	pdev->is_opened = 0;
610 
611 	/*
612 	 * Make sure libusb20_tr_get_pointer() fails:
613 	 */
614 	pdev->nTransfer = 0;
615 
616 	/*
617 	 * The following variable is only used by the libusb v0.1
618 	 * compat layer:
619 	 */
620 	pdev->claimed_interface = 0;
621 
622 	/*
623 	 * The following variable is only used by the libusb v1.0
624 	 * compat layer:
625 	 */
626 	pdev->auto_detach = 0;
627 
628 	return (error);
629 }
630 
631 int
632 libusb20_dev_detach_kernel_driver(struct libusb20_device *pdev, uint8_t ifaceIndex)
633 {
634 	int error;
635 
636 	error = pdev->methods->detach_kernel_driver(pdev, ifaceIndex);
637 	return (error);
638 }
639 
640 struct LIBUSB20_DEVICE_DESC_DECODED *
641 libusb20_dev_get_device_desc(struct libusb20_device *pdev)
642 {
643 	return (&(pdev->ddesc));
644 }
645 
646 int
647 libusb20_dev_get_fd(struct libusb20_device *pdev)
648 {
649 	return (pdev->file);
650 }
651 
652 int
653 libusb20_dev_kernel_driver_active(struct libusb20_device *pdev, uint8_t ifaceIndex)
654 {
655 	int error;
656 
657 	error = pdev->methods->kernel_driver_active(pdev, ifaceIndex);
658 	return (error);
659 }
660 
661 int
662 libusb20_dev_open(struct libusb20_device *pdev, uint16_t nTransferMax)
663 {
664 	struct libusb20_transfer *xfer;
665 	uint32_t size;
666 	uint16_t x;
667 	int error;
668 
669 	if (pdev->is_opened) {
670 		return (LIBUSB20_ERROR_BUSY);
671 	}
672 	if (nTransferMax >= 256) {
673 		return (LIBUSB20_ERROR_INVALID_PARAM);
674 	} else if (nTransferMax != 0) {
675 		size = sizeof(pdev->pTransfer[0]) * nTransferMax;
676 		pdev->pTransfer = malloc(size);
677 		if (pdev->pTransfer == NULL) {
678 			return (LIBUSB20_ERROR_NO_MEM);
679 		}
680 		memset(pdev->pTransfer, 0, size);
681 	}
682 	/* initialise all transfers */
683 	for (x = 0; x != nTransferMax; x++) {
684 
685 		xfer = pdev->pTransfer + x;
686 
687 		xfer->pdev = pdev;
688 		xfer->trIndex = x;
689 		xfer->callback = &dummy_callback;
690 	}
691 
692 	/* set "nTransfer" early */
693 	pdev->nTransfer = nTransferMax;
694 
695 	error = pdev->beMethods->open_device(pdev, nTransferMax);
696 
697 	if (error) {
698 		if (pdev->pTransfer != NULL) {
699 			free(pdev->pTransfer);
700 			pdev->pTransfer = NULL;
701 		}
702 		pdev->file = -1;
703 		pdev->file_ctrl = -1;
704 		pdev->nTransfer = 0;
705 	} else {
706 		pdev->is_opened = 1;
707 	}
708 	return (error);
709 }
710 
711 int
712 libusb20_dev_reset(struct libusb20_device *pdev)
713 {
714 	int error;
715 
716 	error = pdev->methods->reset_device(pdev);
717 	return (error);
718 }
719 
720 int
721 libusb20_dev_check_connected(struct libusb20_device *pdev)
722 {
723 	int error;
724 
725 	error = pdev->methods->check_connected(pdev);
726 	return (error);
727 }
728 
729 int
730 libusb20_dev_set_power_mode(struct libusb20_device *pdev, uint8_t power_mode)
731 {
732 	int error;
733 
734 	error = pdev->methods->set_power_mode(pdev, power_mode);
735 	return (error);
736 }
737 
738 uint8_t
739 libusb20_dev_get_power_mode(struct libusb20_device *pdev)
740 {
741 	int error;
742 	uint8_t power_mode;
743 
744 	error = pdev->methods->get_power_mode(pdev, &power_mode);
745 	if (error)
746 		power_mode = LIBUSB20_POWER_ON;	/* fake power mode */
747 	return (power_mode);
748 }
749 
750 int
751 libusb20_dev_get_port_path(struct libusb20_device *pdev, uint8_t *buf, uint8_t bufsize)
752 {
753 
754 	if (pdev->port_level == 0) {
755 		/*
756 		 * Fallback for backends without port path:
757 		 */
758 		if (bufsize < 2)
759 			return (LIBUSB20_ERROR_OVERFLOW);
760 		buf[0] = pdev->parent_address;
761 		buf[1] = pdev->parent_port;
762 		return (2);
763 	}
764 
765 	/* check if client buffer is too small */
766 	if (pdev->port_level > bufsize)
767 		return (LIBUSB20_ERROR_OVERFLOW);
768 
769 	/* copy port number information */
770 	memcpy(buf, pdev->port_path, pdev->port_level);
771 
772 	return (pdev->port_level);	/* success */
773 }
774 
775 uint16_t
776 libusb20_dev_get_power_usage(struct libusb20_device *pdev)
777 {
778 	int error;
779 	uint16_t power_usage;
780 
781 	error = pdev->methods->get_power_usage(pdev, &power_usage);
782 	if (error)
783 		power_usage = 0;
784 	return (power_usage);
785 }
786 
787 int
788 libusb20_dev_set_alt_index(struct libusb20_device *pdev, uint8_t ifaceIndex, uint8_t altIndex)
789 {
790 	int error;
791 
792 	error = pdev->methods->set_alt_index(pdev, ifaceIndex, altIndex);
793 	return (error);
794 }
795 
796 int
797 libusb20_dev_set_config_index(struct libusb20_device *pdev, uint8_t configIndex)
798 {
799 	int error;
800 
801 	error = pdev->methods->set_config_index(pdev, configIndex);
802 	return (error);
803 }
804 
805 int
806 libusb20_dev_request_sync(struct libusb20_device *pdev,
807     struct LIBUSB20_CONTROL_SETUP_DECODED *setup, void *data,
808     uint16_t *pactlen, uint32_t timeout, uint8_t flags)
809 {
810 	int error;
811 
812 	error = pdev->methods->do_request_sync(pdev,
813 	    setup, data, pactlen, timeout, flags);
814 	return (error);
815 }
816 
817 int
818 libusb20_dev_req_string_sync(struct libusb20_device *pdev,
819     uint8_t str_index, uint16_t langid, void *ptr, uint16_t len)
820 {
821 	struct LIBUSB20_CONTROL_SETUP_DECODED req;
822 	int error;
823 	int flags;
824 
825 	/* make sure memory is initialised */
826 	memset(ptr, 0, len);
827 
828 	if (len < 4) {
829 		/* invalid length */
830 		return (LIBUSB20_ERROR_INVALID_PARAM);
831 	}
832 	LIBUSB20_INIT(LIBUSB20_CONTROL_SETUP, &req);
833 
834 	/*
835 	 * We need to read the USB string in two steps else some USB
836 	 * devices will complain.
837 	 */
838 	req.bmRequestType =
839 	    LIBUSB20_REQUEST_TYPE_STANDARD |
840 	    LIBUSB20_RECIPIENT_DEVICE |
841 	    LIBUSB20_ENDPOINT_IN;
842 	req.bRequest = LIBUSB20_REQUEST_GET_DESCRIPTOR;
843 	req.wValue = (LIBUSB20_DT_STRING << 8) | str_index;
844 	req.wIndex = langid;
845 	req.wLength = 4;		/* bytes */
846 
847 	error = libusb20_dev_request_sync(pdev, &req,
848 	    ptr, NULL, 1000, LIBUSB20_TRANSFER_SINGLE_SHORT_NOT_OK);
849 	if (error) {
850 		/* try to request full string */
851 		req.wLength = 255;
852 		flags = 0;
853 	} else {
854 		/* extract length and request full string */
855 		req.wLength = *(uint8_t *)ptr;
856 		flags = LIBUSB20_TRANSFER_SINGLE_SHORT_NOT_OK;
857 	}
858 	if (req.wLength > len) {
859 		/* partial string read */
860 		req.wLength = len;
861 	}
862 	error = libusb20_dev_request_sync(pdev, &req, ptr, NULL, 1000, flags);
863 	if (error)
864 		return (error);
865 
866 	if (((uint8_t *)ptr)[1] != LIBUSB20_DT_STRING)
867 		return (LIBUSB20_ERROR_OTHER);
868 	return (0);			/* success */
869 }
870 
871 int
872 libusb20_dev_req_string_simple_sync(struct libusb20_device *pdev,
873     uint8_t str_index, void *ptr, uint16_t len)
874 {
875 	char *buf;
876 	int error;
877 	uint16_t langid;
878 	uint16_t n;
879 	uint16_t i;
880 	uint16_t c;
881 	uint8_t temp[255];
882 	uint8_t swap;
883 
884 	/* the following code derives from the FreeBSD USB kernel */
885 
886 	if ((len < 1) || (ptr == NULL)) {
887 		/* too short buffer */
888 		return (LIBUSB20_ERROR_INVALID_PARAM);
889 	}
890 	error = libusb20_dev_req_string_sync(pdev,
891 	    0, 0, temp, sizeof(temp));
892 	if (error < 0) {
893 		*(uint8_t *)ptr = 0;	/* zero terminate */
894 		return (error);
895 	}
896 	langid = temp[2] | (temp[3] << 8);
897 
898 	error = libusb20_dev_req_string_sync(pdev, str_index,
899 	    langid, temp, sizeof(temp));
900 	if (error < 0) {
901 		*(uint8_t *)ptr = 0;	/* zero terminate */
902 		return (error);
903 	}
904 	if (temp[0] < 2) {
905 		/* string length is too short */
906 		*(uint8_t *)ptr = 0;	/* zero terminate */
907 		return (LIBUSB20_ERROR_OTHER);
908 	}
909 	/* reserve one byte for terminating zero */
910 	len--;
911 
912 	/* find maximum length */
913 	n = (temp[0] / 2) - 1;
914 	if (n > len) {
915 		n = len;
916 	}
917 	/* reset swap state */
918 	swap = 3;
919 
920 	/* setup output buffer pointer */
921 	buf = ptr;
922 
923 	/* convert and filter */
924 	for (i = 0; (i != n); i++) {
925 		c = temp[(2 * i) + 2] | (temp[(2 * i) + 3] << 8);
926 
927 		/* convert from Unicode, handle buggy strings */
928 		if (((c & 0xff00) == 0) && (swap & 1)) {
929 			/* Little Endian, default */
930 			*buf = c;
931 			swap = 1;
932 		} else if (((c & 0x00ff) == 0) && (swap & 2)) {
933 			/* Big Endian */
934 			*buf = c >> 8;
935 			swap = 2;
936 		} else {
937 			/* skip invalid character */
938 			continue;
939 		}
940 		/*
941 		 * Filter by default - we don't allow greater and less than
942 		 * signs because they might confuse the dmesg printouts!
943 		 */
944 		if ((*buf == '<') || (*buf == '>') || (!isprint(*buf))) {
945 			/* skip invalid character */
946 			continue;
947 		}
948 		buf++;
949 	}
950 	*buf = 0;			/* zero terminate string */
951 
952 	return (0);
953 }
954 
955 struct libusb20_config *
956 libusb20_dev_alloc_config(struct libusb20_device *pdev, uint8_t configIndex)
957 {
958 	struct libusb20_config *retval = NULL;
959 	uint8_t *ptr;
960 	uint16_t len;
961 	uint8_t do_close;
962 	int error;
963 
964 	/*
965 	 * Catch invalid configuration descriptor reads early on to
966 	 * avoid issues with devices that don't check for a valid USB
967 	 * configuration read request.
968 	 */
969 	if (configIndex >= pdev->ddesc.bNumConfigurations)
970 		return (NULL);
971 
972 	if (!pdev->is_opened) {
973 		error = libusb20_dev_open(pdev, 0);
974 		if (error) {
975 			return (NULL);
976 		}
977 		do_close = 1;
978 	} else {
979 		do_close = 0;
980 	}
981 	error = pdev->methods->get_config_desc_full(pdev,
982 	    &ptr, &len, configIndex);
983 
984 	if (error) {
985 		goto done;
986 	}
987 	/* parse new config descriptor */
988 	retval = libusb20_parse_config_desc(ptr);
989 
990 	/* free config descriptor */
991 	free(ptr);
992 
993 done:
994 	if (do_close) {
995 		error = libusb20_dev_close(pdev);
996 	}
997 	return (retval);
998 }
999 
1000 struct libusb20_device *
1001 libusb20_dev_alloc(void)
1002 {
1003 	struct libusb20_device *pdev;
1004 
1005 	pdev = malloc(sizeof(*pdev));
1006 	if (pdev == NULL) {
1007 		return (NULL);
1008 	}
1009 	memset(pdev, 0, sizeof(*pdev));
1010 
1011 	pdev->file = -1;
1012 	pdev->file_ctrl = -1;
1013 	pdev->methods = &libusb20_dummy_methods;
1014 	return (pdev);
1015 }
1016 
1017 uint8_t
1018 libusb20_dev_get_config_index(struct libusb20_device *pdev)
1019 {
1020 	int error;
1021 	uint8_t cfg_index;
1022 	uint8_t do_close;
1023 
1024 	if (!pdev->is_opened) {
1025 		error = libusb20_dev_open(pdev, 0);
1026 		if (error == 0) {
1027 			do_close = 1;
1028 		} else {
1029 			do_close = 0;
1030 		}
1031 	} else {
1032 		do_close = 0;
1033 	}
1034 
1035 	error = pdev->methods->get_config_index(pdev, &cfg_index);
1036 	if (error)
1037 		cfg_index = 0xFF;	/* current config index */
1038 	if (do_close) {
1039 		if (libusb20_dev_close(pdev)) {
1040 			/* ignore */
1041 		}
1042 	}
1043 	return (cfg_index);
1044 }
1045 
1046 uint8_t
1047 libusb20_dev_get_mode(struct libusb20_device *pdev)
1048 {
1049 	return (pdev->usb_mode);
1050 }
1051 
1052 uint8_t
1053 libusb20_dev_get_speed(struct libusb20_device *pdev)
1054 {
1055 	return (pdev->usb_speed);
1056 }
1057 
1058 int
1059 libusb20_dev_get_stats(struct libusb20_device *pdev, struct libusb20_device_stats *pstats)
1060 {
1061 	uint8_t do_close;
1062 	int error;
1063 
1064 	if (!pdev->is_opened) {
1065 		error = libusb20_dev_open(pdev, 0);
1066 		if (error == 0) {
1067 			do_close = 1;
1068 		} else {
1069 			do_close = 0;
1070 		}
1071 	} else {
1072 		do_close = 0;
1073 	}
1074 
1075 	error = pdev->methods->get_stats(pdev, pstats);
1076 
1077 	if (do_close)
1078 		(void) libusb20_dev_close(pdev);
1079 
1080 	return (error);
1081 }
1082 
1083 /* if this function returns an error, the device is gone */
1084 int
1085 libusb20_dev_process(struct libusb20_device *pdev)
1086 {
1087 	int error;
1088 
1089 	error = pdev->methods->process(pdev);
1090 	return (error);
1091 }
1092 
1093 void
1094 libusb20_dev_wait_process(struct libusb20_device *pdev, int timeout)
1095 {
1096 	struct pollfd pfd[1];
1097 
1098 	if (!pdev->is_opened) {
1099 		return;
1100 	}
1101 	pfd[0].fd = pdev->file;
1102 	pfd[0].events = (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM);
1103 	pfd[0].revents = 0;
1104 
1105 	if (poll(pfd, 1, timeout)) {
1106 		/* ignore any error */
1107 	}
1108 	return;
1109 }
1110 
1111 void
1112 libusb20_dev_free(struct libusb20_device *pdev)
1113 {
1114 	if (pdev == NULL) {
1115 		/* be NULL safe */
1116 		return;
1117 	}
1118 	if (pdev->is_opened) {
1119 		if (libusb20_dev_close(pdev)) {
1120 			/* ignore any errors */
1121 		}
1122 	}
1123 	free(pdev);
1124 	return;
1125 }
1126 
1127 int
1128 libusb20_dev_get_info(struct libusb20_device *pdev,
1129     struct usb_device_info *pinfo)
1130 {
1131 	if (pinfo == NULL)
1132 		return (LIBUSB20_ERROR_INVALID_PARAM);
1133 
1134 	return (pdev->beMethods->dev_get_info(pdev, pinfo));
1135 }
1136 
1137 const char *
1138 libusb20_dev_get_backend_name(struct libusb20_device *pdev)
1139 {
1140 	return (pdev->beMethods->get_backend_name());
1141 }
1142 
1143 const char *
1144 libusb20_dev_get_desc(struct libusb20_device *pdev)
1145 {
1146 	return (pdev->usb_desc);
1147 }
1148 
1149 void
1150 libusb20_dev_set_debug(struct libusb20_device *pdev, int debug)
1151 {
1152 	pdev->debug = debug;
1153 	return;
1154 }
1155 
1156 int
1157 libusb20_dev_get_debug(struct libusb20_device *pdev)
1158 {
1159 	return (pdev->debug);
1160 }
1161 
1162 uint8_t
1163 libusb20_dev_get_address(struct libusb20_device *pdev)
1164 {
1165 	return (pdev->device_address);
1166 }
1167 
1168 uint8_t
1169 libusb20_dev_get_parent_address(struct libusb20_device *pdev)
1170 {
1171 	return (pdev->parent_address);
1172 }
1173 
1174 uint8_t
1175 libusb20_dev_get_parent_port(struct libusb20_device *pdev)
1176 {
1177 	return (pdev->parent_port);
1178 }
1179 
1180 uint8_t
1181 libusb20_dev_get_bus_number(struct libusb20_device *pdev)
1182 {
1183 	return (pdev->bus_number);
1184 }
1185 
1186 int
1187 libusb20_dev_get_iface_desc(struct libusb20_device *pdev,
1188     uint8_t iface_index, char *buf, uint8_t len)
1189 {
1190 	if ((buf == NULL) || (len == 0))
1191 		return (LIBUSB20_ERROR_INVALID_PARAM);
1192 
1193 	buf[0] = 0;		/* set default string value */
1194 
1195 	return (pdev->beMethods->dev_get_iface_desc(
1196 	    pdev, iface_index, buf, len));
1197 }
1198 
1199 /* USB backend operations */
1200 
1201 int
1202 libusb20_be_get_dev_quirk(struct libusb20_backend *pbe,
1203     uint16_t quirk_index, struct libusb20_quirk *pq)
1204 {
1205 	return (pbe->methods->root_get_dev_quirk(pbe, quirk_index, pq));
1206 }
1207 
1208 int
1209 libusb20_be_get_quirk_name(struct libusb20_backend *pbe,
1210     uint16_t quirk_index, struct libusb20_quirk *pq)
1211 {
1212 	return (pbe->methods->root_get_quirk_name(pbe, quirk_index, pq));
1213 }
1214 
1215 int
1216 libusb20_be_add_dev_quirk(struct libusb20_backend *pbe,
1217     struct libusb20_quirk *pq)
1218 {
1219 	return (pbe->methods->root_add_dev_quirk(pbe, pq));
1220 }
1221 
1222 int
1223 libusb20_be_remove_dev_quirk(struct libusb20_backend *pbe,
1224     struct libusb20_quirk *pq)
1225 {
1226 	return (pbe->methods->root_remove_dev_quirk(pbe, pq));
1227 }
1228 
1229 int
1230 libusb20_be_set_template(struct libusb20_backend *pbe, int temp)
1231 {
1232 	return (pbe->methods->root_set_template(pbe, temp));
1233 }
1234 
1235 int
1236 libusb20_be_get_template(struct libusb20_backend *pbe, int *ptemp)
1237 {
1238 	int temp;
1239 
1240 	if (ptemp == NULL)
1241 		ptemp = &temp;
1242 
1243 	return (pbe->methods->root_get_template(pbe, ptemp));
1244 }
1245 
1246 struct libusb20_device *
1247 libusb20_be_device_foreach(struct libusb20_backend *pbe, struct libusb20_device *pdev)
1248 {
1249 	if (pbe == NULL) {
1250 		pdev = NULL;
1251 	} else if (pdev == NULL) {
1252 		pdev = TAILQ_FIRST(&(pbe->usb_devs));
1253 	} else {
1254 		pdev = TAILQ_NEXT(pdev, dev_entry);
1255 	}
1256 	return (pdev);
1257 }
1258 
1259 struct libusb20_backend *
1260 libusb20_be_alloc(const struct libusb20_backend_methods *methods)
1261 {
1262 	struct libusb20_backend *pbe;
1263 
1264 	pbe = malloc(sizeof(*pbe));
1265 	if (pbe == NULL) {
1266 		return (NULL);
1267 	}
1268 	memset(pbe, 0, sizeof(*pbe));
1269 
1270 	TAILQ_INIT(&(pbe->usb_devs));
1271 
1272 	pbe->methods = methods;		/* set backend methods */
1273 
1274 	/* do the initial device scan */
1275 	if (pbe->methods->init_backend) {
1276 		pbe->methods->init_backend(pbe);
1277 	}
1278 	return (pbe);
1279 }
1280 
1281 struct libusb20_backend *
1282 libusb20_be_alloc_linux(void)
1283 {
1284 	return (NULL);
1285 }
1286 
1287 struct libusb20_backend *
1288 libusb20_be_alloc_ugen20(void)
1289 {
1290 	return (libusb20_be_alloc(&libusb20_ugen20_backend));
1291 }
1292 
1293 struct libusb20_backend *
1294 libusb20_be_alloc_default(void)
1295 {
1296 	struct libusb20_backend *pbe;
1297 
1298 #ifdef __linux__
1299 	pbe = libusb20_be_alloc_linux();
1300 	if (pbe) {
1301 		return (pbe);
1302 	}
1303 #endif
1304 	pbe = libusb20_be_alloc_ugen20();
1305 	if (pbe) {
1306 		return (pbe);
1307 	}
1308 	return (NULL);			/* no backend found */
1309 }
1310 
1311 void
1312 libusb20_be_free(struct libusb20_backend *pbe)
1313 {
1314 	struct libusb20_device *pdev;
1315 
1316 	if (pbe == NULL) {
1317 		/* be NULL safe */
1318 		return;
1319 	}
1320 	while ((pdev = libusb20_be_device_foreach(pbe, NULL))) {
1321 		libusb20_be_dequeue_device(pbe, pdev);
1322 		libusb20_dev_free(pdev);
1323 	}
1324 	if (pbe->methods->exit_backend) {
1325 		pbe->methods->exit_backend(pbe);
1326 	}
1327 	/* free backend */
1328 	free(pbe);
1329 }
1330 
1331 void
1332 libusb20_be_enqueue_device(struct libusb20_backend *pbe, struct libusb20_device *pdev)
1333 {
1334 	pdev->beMethods = pbe->methods;	/* copy backend methods */
1335 	TAILQ_INSERT_TAIL(&(pbe->usb_devs), pdev, dev_entry);
1336 }
1337 
1338 void
1339 libusb20_be_dequeue_device(struct libusb20_backend *pbe,
1340     struct libusb20_device *pdev)
1341 {
1342 	TAILQ_REMOVE(&(pbe->usb_devs), pdev, dev_entry);
1343 }
1344 
1345 const char *
1346 libusb20_strerror(int code)
1347 {
1348 	switch (code) {
1349 	case LIBUSB20_SUCCESS:
1350 		return ("Success");
1351 	case LIBUSB20_ERROR_IO:
1352 		return ("I/O error");
1353 	case LIBUSB20_ERROR_INVALID_PARAM:
1354 		return ("Invalid parameter");
1355 	case LIBUSB20_ERROR_ACCESS:
1356 		return ("Permissions error");
1357 	case LIBUSB20_ERROR_NO_DEVICE:
1358 		return ("No device");
1359 	case LIBUSB20_ERROR_NOT_FOUND:
1360 		return ("Not found");
1361 	case LIBUSB20_ERROR_BUSY:
1362 		return ("Device busy");
1363 	case LIBUSB20_ERROR_TIMEOUT:
1364 		return ("Timeout");
1365 	case LIBUSB20_ERROR_OVERFLOW:
1366 		return ("Overflow");
1367 	case LIBUSB20_ERROR_PIPE:
1368 		return ("Pipe error");
1369 	case LIBUSB20_ERROR_INTERRUPTED:
1370 		return ("Interrupted");
1371 	case LIBUSB20_ERROR_NO_MEM:
1372 		return ("Out of memory");
1373 	case LIBUSB20_ERROR_NOT_SUPPORTED:
1374 		return ("Not supported");
1375 	case LIBUSB20_ERROR_OTHER:
1376 		return ("Other error");
1377 	default:
1378 		return ("Unknown error");
1379 	}
1380 }
1381 
1382 const char *
1383 libusb20_error_name(int code)
1384 {
1385 	switch (code) {
1386 	case LIBUSB20_SUCCESS:
1387 		return ("LIBUSB20_SUCCESS");
1388 	case LIBUSB20_ERROR_IO:
1389 		return ("LIBUSB20_ERROR_IO");
1390 	case LIBUSB20_ERROR_INVALID_PARAM:
1391 		return ("LIBUSB20_ERROR_INVALID_PARAM");
1392 	case LIBUSB20_ERROR_ACCESS:
1393 		return ("LIBUSB20_ERROR_ACCESS");
1394 	case LIBUSB20_ERROR_NO_DEVICE:
1395 		return ("LIBUSB20_ERROR_NO_DEVICE");
1396 	case LIBUSB20_ERROR_NOT_FOUND:
1397 		return ("LIBUSB20_ERROR_NOT_FOUND");
1398 	case LIBUSB20_ERROR_BUSY:
1399 		return ("LIBUSB20_ERROR_BUSY");
1400 	case LIBUSB20_ERROR_TIMEOUT:
1401 		return ("LIBUSB20_ERROR_TIMEOUT");
1402 	case LIBUSB20_ERROR_OVERFLOW:
1403 		return ("LIBUSB20_ERROR_OVERFLOW");
1404 	case LIBUSB20_ERROR_PIPE:
1405 		return ("LIBUSB20_ERROR_PIPE");
1406 	case LIBUSB20_ERROR_INTERRUPTED:
1407 		return ("LIBUSB20_ERROR_INTERRUPTED");
1408 	case LIBUSB20_ERROR_NO_MEM:
1409 		return ("LIBUSB20_ERROR_NO_MEM");
1410 	case LIBUSB20_ERROR_NOT_SUPPORTED:
1411 		return ("LIBUSB20_ERROR_NOT_SUPPORTED");
1412 	case LIBUSB20_ERROR_OTHER:
1413 		return ("LIBUSB20_ERROR_OTHER");
1414 	default:
1415 		return ("LIBUSB20_ERROR_UNKNOWN");
1416 	}
1417 }
1418