xref: /freebsd/sys/dev/usb/usb_request.c (revision 4ed925457ab06e83238a5db33e89ccc94b99a713)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
4  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
5  * Copyright (c) 2008 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 #include <sys/stdint.h>
30 #include <sys/stddef.h>
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/bus.h>
37 #include <sys/linker_set.h>
38 #include <sys/module.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/condvar.h>
42 #include <sys/sysctl.h>
43 #include <sys/sx.h>
44 #include <sys/unistd.h>
45 #include <sys/callout.h>
46 #include <sys/malloc.h>
47 #include <sys/priv.h>
48 
49 #include <dev/usb/usb.h>
50 #include <dev/usb/usbdi.h>
51 #include <dev/usb/usbdi_util.h>
52 #include <dev/usb/usb_ioctl.h>
53 #include <dev/usb/usbhid.h>
54 
55 #define	USB_DEBUG_VAR usb_debug
56 
57 #include <dev/usb/usb_core.h>
58 #include <dev/usb/usb_busdma.h>
59 #include <dev/usb/usb_request.h>
60 #include <dev/usb/usb_process.h>
61 #include <dev/usb/usb_transfer.h>
62 #include <dev/usb/usb_debug.h>
63 #include <dev/usb/usb_device.h>
64 #include <dev/usb/usb_util.h>
65 #include <dev/usb/usb_dynamic.h>
66 
67 #include <dev/usb/usb_controller.h>
68 #include <dev/usb/usb_bus.h>
69 #include <sys/ctype.h>
70 
71 #if USB_DEBUG
72 static int usb_pr_poll_delay = USB_PORT_RESET_DELAY;
73 static int usb_pr_recovery_delay = USB_PORT_RESET_RECOVERY;
74 static int usb_ss_delay = 0;
75 
76 SYSCTL_INT(_hw_usb, OID_AUTO, pr_poll_delay, CTLFLAG_RW,
77     &usb_pr_poll_delay, 0, "USB port reset poll delay in ms");
78 SYSCTL_INT(_hw_usb, OID_AUTO, pr_recovery_delay, CTLFLAG_RW,
79     &usb_pr_recovery_delay, 0, "USB port reset recovery delay in ms");
80 SYSCTL_INT(_hw_usb, OID_AUTO, ss_delay, CTLFLAG_RW,
81     &usb_ss_delay, 0, "USB status stage delay in ms");
82 #endif
83 
84 /*------------------------------------------------------------------------*
85  *	usbd_do_request_callback
86  *
87  * This function is the USB callback for generic USB Host control
88  * transfers.
89  *------------------------------------------------------------------------*/
90 void
91 usbd_do_request_callback(struct usb_xfer *xfer, usb_error_t error)
92 {
93 	;				/* workaround for a bug in "indent" */
94 
95 	DPRINTF("st=%u\n", USB_GET_STATE(xfer));
96 
97 	switch (USB_GET_STATE(xfer)) {
98 	case USB_ST_SETUP:
99 		usbd_transfer_submit(xfer);
100 		break;
101 	default:
102 		cv_signal(xfer->xroot->udev->default_cv);
103 		break;
104 	}
105 }
106 
107 /*------------------------------------------------------------------------*
108  *	usb_do_clear_stall_callback
109  *
110  * This function is the USB callback for generic clear stall requests.
111  *------------------------------------------------------------------------*/
112 void
113 usb_do_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
114 {
115 	struct usb_device_request req;
116 	struct usb_device *udev;
117 	struct usb_endpoint *ep;
118 	struct usb_endpoint *ep_end;
119 	struct usb_endpoint *ep_first;
120 	uint8_t to;
121 
122 	udev = xfer->xroot->udev;
123 
124 	USB_BUS_LOCK(udev->bus);
125 
126 	/* round robin endpoint clear stall */
127 
128 	ep = udev->ep_curr;
129 	ep_end = udev->endpoints + udev->endpoints_max;
130 	ep_first = udev->endpoints;
131 	to = udev->endpoints_max;
132 
133 	switch (USB_GET_STATE(xfer)) {
134 	case USB_ST_TRANSFERRED:
135 		if (ep == NULL)
136 			goto tr_setup;		/* device was unconfigured */
137 		if (ep->edesc &&
138 		    ep->is_stalled) {
139 			ep->toggle_next = 0;
140 			ep->is_stalled = 0;
141 			/* start up the current or next transfer, if any */
142 			usb_command_wrapper(&ep->endpoint_q,
143 			    ep->endpoint_q.curr);
144 		}
145 		ep++;
146 
147 	case USB_ST_SETUP:
148 tr_setup:
149 		if (to == 0)
150 			break;			/* no endpoints - nothing to do */
151 		if ((ep < ep_first) || (ep >= ep_end))
152 			ep = ep_first;	/* endpoint wrapped around */
153 		if (ep->edesc &&
154 		    ep->is_stalled) {
155 
156 			/* setup a clear-stall packet */
157 
158 			req.bmRequestType = UT_WRITE_ENDPOINT;
159 			req.bRequest = UR_CLEAR_FEATURE;
160 			USETW(req.wValue, UF_ENDPOINT_HALT);
161 			req.wIndex[0] = ep->edesc->bEndpointAddress;
162 			req.wIndex[1] = 0;
163 			USETW(req.wLength, 0);
164 
165 			/* copy in the transfer */
166 
167 			usbd_copy_in(xfer->frbuffers, 0, &req, sizeof(req));
168 
169 			/* set length */
170 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
171 			xfer->nframes = 1;
172 			USB_BUS_UNLOCK(udev->bus);
173 
174 			usbd_transfer_submit(xfer);
175 
176 			USB_BUS_LOCK(udev->bus);
177 			break;
178 		}
179 		ep++;
180 		to--;
181 		goto tr_setup;
182 
183 	default:
184 		if (xfer->error == USB_ERR_CANCELLED) {
185 			break;
186 		}
187 		goto tr_setup;
188 	}
189 
190 	/* store current endpoint */
191 	udev->ep_curr = ep;
192 	USB_BUS_UNLOCK(udev->bus);
193 }
194 
195 static usb_handle_req_t *
196 usbd_get_hr_func(struct usb_device *udev)
197 {
198 	/* figure out if there is a Handle Request function */
199 	if (udev->flags.usb_mode == USB_MODE_DEVICE)
200 		return (usb_temp_get_desc_p);
201 	else if (udev->parent_hub == NULL)
202 		return (udev->bus->methods->roothub_exec);
203 	else
204 		return (NULL);
205 }
206 
207 /*------------------------------------------------------------------------*
208  *	usbd_do_request_flags and usbd_do_request
209  *
210  * Description of arguments passed to these functions:
211  *
212  * "udev" - this is the "usb_device" structure pointer on which the
213  * request should be performed. It is possible to call this function
214  * in both Host Side mode and Device Side mode.
215  *
216  * "mtx" - if this argument is non-NULL the mutex pointed to by it
217  * will get dropped and picked up during the execution of this
218  * function, hence this function sometimes needs to sleep. If this
219  * argument is NULL it has no effect.
220  *
221  * "req" - this argument must always be non-NULL and points to an
222  * 8-byte structure holding the USB request to be done. The USB
223  * request structure has a bit telling the direction of the USB
224  * request, if it is a read or a write.
225  *
226  * "data" - if the "wLength" part of the structure pointed to by "req"
227  * is non-zero this argument must point to a valid kernel buffer which
228  * can hold at least "wLength" bytes. If "wLength" is zero "data" can
229  * be NULL.
230  *
231  * "flags" - here is a list of valid flags:
232  *
233  *  o USB_SHORT_XFER_OK: allows the data transfer to be shorter than
234  *  specified
235  *
236  *  o USB_DELAY_STATUS_STAGE: allows the status stage to be performed
237  *  at a later point in time. This is tunable by the "hw.usb.ss_delay"
238  *  sysctl. This flag is mostly useful for debugging.
239  *
240  *  o USB_USER_DATA_PTR: treat the "data" pointer like a userland
241  *  pointer.
242  *
243  * "actlen" - if non-NULL the actual transfer length will be stored in
244  * the 16-bit unsigned integer pointed to by "actlen". This
245  * information is mostly useful when the "USB_SHORT_XFER_OK" flag is
246  * used.
247  *
248  * "timeout" - gives the timeout for the control transfer in
249  * milliseconds. A "timeout" value less than 50 milliseconds is
250  * treated like a 50 millisecond timeout. A "timeout" value greater
251  * than 30 seconds is treated like a 30 second timeout. This USB stack
252  * does not allow control requests without a timeout.
253  *
254  * NOTE: This function is thread safe. All calls to
255  * "usbd_do_request_flags" will be serialised by the use of an
256  * internal "sx_lock".
257  *
258  * Returns:
259  *    0: Success
260  * Else: Failure
261  *------------------------------------------------------------------------*/
262 usb_error_t
263 usbd_do_request_flags(struct usb_device *udev, struct mtx *mtx,
264     struct usb_device_request *req, void *data, uint16_t flags,
265     uint16_t *actlen, usb_timeout_t timeout)
266 {
267 	usb_handle_req_t *hr_func;
268 	struct usb_xfer *xfer;
269 	const void *desc;
270 	int err = 0;
271 	usb_ticks_t start_ticks;
272 	usb_ticks_t delta_ticks;
273 	usb_ticks_t max_ticks;
274 	uint16_t length;
275 	uint16_t temp;
276 
277 	if (timeout < 50) {
278 		/* timeout is too small */
279 		timeout = 50;
280 	}
281 	if (timeout > 30000) {
282 		/* timeout is too big */
283 		timeout = 30000;
284 	}
285 	length = UGETW(req->wLength);
286 
287 	DPRINTFN(5, "udev=%p bmRequestType=0x%02x bRequest=0x%02x "
288 	    "wValue=0x%02x%02x wIndex=0x%02x%02x wLength=0x%02x%02x\n",
289 	    udev, req->bmRequestType, req->bRequest,
290 	    req->wValue[1], req->wValue[0],
291 	    req->wIndex[1], req->wIndex[0],
292 	    req->wLength[1], req->wLength[0]);
293 
294 	/* Check if the device is still alive */
295 	if (udev->state < USB_STATE_POWERED) {
296 		DPRINTF("usb device has gone\n");
297 		return (USB_ERR_NOT_CONFIGURED);
298 	}
299 
300 	/*
301 	 * Set "actlen" to a known value in case the caller does not
302 	 * check the return value:
303 	 */
304 	if (actlen)
305 		*actlen = 0;
306 
307 #if (USB_HAVE_USER_IO == 0)
308 	if (flags & USB_USER_DATA_PTR)
309 		return (USB_ERR_INVAL);
310 #endif
311 	if (mtx) {
312 		mtx_unlock(mtx);
313 		if (mtx != &Giant) {
314 			mtx_assert(mtx, MA_NOTOWNED);
315 		}
316 	}
317 	/*
318 	 * Grab the default sx-lock so that serialisation
319 	 * is achieved when multiple threads are involved:
320 	 */
321 
322 	sx_xlock(udev->default_sx);
323 
324 	hr_func = usbd_get_hr_func(udev);
325 
326 	if (hr_func != NULL) {
327 		DPRINTF("Handle Request function is set\n");
328 
329 		desc = NULL;
330 		temp = 0;
331 
332 		if (!(req->bmRequestType & UT_READ)) {
333 			if (length != 0) {
334 				DPRINTFN(1, "The handle request function "
335 				    "does not support writing data!\n");
336 				err = USB_ERR_INVAL;
337 				goto done;
338 			}
339 		}
340 
341 		/* The root HUB code needs the BUS lock locked */
342 
343 		USB_BUS_LOCK(udev->bus);
344 		err = (hr_func) (udev, req, &desc, &temp);
345 		USB_BUS_UNLOCK(udev->bus);
346 
347 		if (err)
348 			goto done;
349 
350 		if (length > temp) {
351 			if (!(flags & USB_SHORT_XFER_OK)) {
352 				err = USB_ERR_SHORT_XFER;
353 				goto done;
354 			}
355 			length = temp;
356 		}
357 		if (actlen)
358 			*actlen = length;
359 
360 		if (length > 0) {
361 #if USB_HAVE_USER_IO
362 			if (flags & USB_USER_DATA_PTR) {
363 				if (copyout(desc, data, length)) {
364 					err = USB_ERR_INVAL;
365 					goto done;
366 				}
367 			} else
368 #endif
369 				bcopy(desc, data, length);
370 		}
371 		goto done;		/* success */
372 	}
373 
374 	/*
375 	 * Setup a new USB transfer or use the existing one, if any:
376 	 */
377 	usbd_default_transfer_setup(udev);
378 
379 	xfer = udev->default_xfer[0];
380 	if (xfer == NULL) {
381 		/* most likely out of memory */
382 		err = USB_ERR_NOMEM;
383 		goto done;
384 	}
385 	USB_XFER_LOCK(xfer);
386 
387 	if (flags & USB_DELAY_STATUS_STAGE)
388 		xfer->flags.manual_status = 1;
389 	else
390 		xfer->flags.manual_status = 0;
391 
392 	if (flags & USB_SHORT_XFER_OK)
393 		xfer->flags.short_xfer_ok = 1;
394 	else
395 		xfer->flags.short_xfer_ok = 0;
396 
397 	xfer->timeout = timeout;
398 
399 	start_ticks = ticks;
400 
401 	max_ticks = USB_MS_TO_TICKS(timeout);
402 
403 	usbd_copy_in(xfer->frbuffers, 0, req, sizeof(*req));
404 
405 	usbd_xfer_set_frame_len(xfer, 0, sizeof(*req));
406 	xfer->nframes = 2;
407 
408 	while (1) {
409 		temp = length;
410 		if (temp > xfer->max_data_length) {
411 			temp = usbd_xfer_max_len(xfer);
412 		}
413 		usbd_xfer_set_frame_len(xfer, 1, temp);
414 
415 		if (temp > 0) {
416 			if (!(req->bmRequestType & UT_READ)) {
417 #if USB_HAVE_USER_IO
418 				if (flags & USB_USER_DATA_PTR) {
419 					USB_XFER_UNLOCK(xfer);
420 					err = usbd_copy_in_user(xfer->frbuffers + 1,
421 					    0, data, temp);
422 					USB_XFER_LOCK(xfer);
423 					if (err) {
424 						err = USB_ERR_INVAL;
425 						break;
426 					}
427 				} else
428 #endif
429 					usbd_copy_in(xfer->frbuffers + 1,
430 					    0, data, temp);
431 			}
432 			xfer->nframes = 2;
433 		} else {
434 			if (xfer->frlengths[0] == 0) {
435 				if (xfer->flags.manual_status) {
436 #if USB_DEBUG
437 					int temp;
438 
439 					temp = usb_ss_delay;
440 					if (temp > 5000) {
441 						temp = 5000;
442 					}
443 					if (temp > 0) {
444 						usb_pause_mtx(
445 						    xfer->xroot->xfer_mtx,
446 						    USB_MS_TO_TICKS(temp));
447 					}
448 #endif
449 					xfer->flags.manual_status = 0;
450 				} else {
451 					break;
452 				}
453 			}
454 			xfer->nframes = 1;
455 		}
456 
457 		usbd_transfer_start(xfer);
458 
459 		while (usbd_transfer_pending(xfer)) {
460 			cv_wait(udev->default_cv,
461 			    xfer->xroot->xfer_mtx);
462 		}
463 
464 		err = xfer->error;
465 
466 		if (err) {
467 			break;
468 		}
469 		/* subtract length of SETUP packet, if any */
470 
471 		if (xfer->aframes > 0) {
472 			xfer->actlen -= xfer->frlengths[0];
473 		} else {
474 			xfer->actlen = 0;
475 		}
476 
477 		/* check for short packet */
478 
479 		if (temp > xfer->actlen) {
480 			temp = xfer->actlen;
481 			length = temp;
482 		}
483 		if (temp > 0) {
484 			if (req->bmRequestType & UT_READ) {
485 #if USB_HAVE_USER_IO
486 				if (flags & USB_USER_DATA_PTR) {
487 					USB_XFER_UNLOCK(xfer);
488 					err = usbd_copy_out_user(xfer->frbuffers + 1,
489 					    0, data, temp);
490 					USB_XFER_LOCK(xfer);
491 					if (err) {
492 						err = USB_ERR_INVAL;
493 						break;
494 					}
495 				} else
496 #endif
497 					usbd_copy_out(xfer->frbuffers + 1,
498 					    0, data, temp);
499 			}
500 		}
501 		/*
502 		 * Clear "frlengths[0]" so that we don't send the setup
503 		 * packet again:
504 		 */
505 		usbd_xfer_set_frame_len(xfer, 0, 0);
506 
507 		/* update length and data pointer */
508 		length -= temp;
509 		data = USB_ADD_BYTES(data, temp);
510 
511 		if (actlen) {
512 			(*actlen) += temp;
513 		}
514 		/* check for timeout */
515 
516 		delta_ticks = ticks - start_ticks;
517 		if (delta_ticks > max_ticks) {
518 			if (!err) {
519 				err = USB_ERR_TIMEOUT;
520 			}
521 		}
522 		if (err) {
523 			break;
524 		}
525 	}
526 
527 	if (err) {
528 		/*
529 		 * Make sure that the control endpoint is no longer
530 		 * blocked in case of a non-transfer related error:
531 		 */
532 		usbd_transfer_stop(xfer);
533 	}
534 	USB_XFER_UNLOCK(xfer);
535 
536 done:
537 	sx_xunlock(udev->default_sx);
538 
539 	if (mtx) {
540 		mtx_lock(mtx);
541 	}
542 	return ((usb_error_t)err);
543 }
544 
545 /*------------------------------------------------------------------------*
546  *	usbd_do_request_proc - factored out code
547  *
548  * This function is factored out code. It does basically the same like
549  * usbd_do_request_flags, except it will check the status of the
550  * passed process argument before doing the USB request. If the
551  * process is draining the USB_ERR_IOERROR code will be returned. It
552  * is assumed that the mutex associated with the process is locked
553  * when calling this function.
554  *------------------------------------------------------------------------*/
555 usb_error_t
556 usbd_do_request_proc(struct usb_device *udev, struct usb_process *pproc,
557     struct usb_device_request *req, void *data, uint16_t flags,
558     uint16_t *actlen, usb_timeout_t timeout)
559 {
560 	usb_error_t err;
561 	uint16_t len;
562 
563 	/* get request data length */
564 	len = UGETW(req->wLength);
565 
566 	/* check if the device is being detached */
567 	if (usb_proc_is_gone(pproc)) {
568 		err = USB_ERR_IOERROR;
569 		goto done;
570 	}
571 
572 	/* forward the USB request */
573 	err = usbd_do_request_flags(udev, pproc->up_mtx,
574 	    req, data, flags, actlen, timeout);
575 
576 done:
577 	/* on failure we zero the data */
578 	/* on short packet we zero the unused data */
579 	if ((len != 0) && (req->bmRequestType & UE_DIR_IN)) {
580 		if (err)
581 			memset(data, 0, len);
582 		else if (actlen && *actlen != len)
583 			memset(((uint8_t *)data) + *actlen, 0, len - *actlen);
584 	}
585 	return (err);
586 }
587 
588 /*------------------------------------------------------------------------*
589  *	usbd_req_reset_port
590  *
591  * This function will instruct an USB HUB to perform a reset sequence
592  * on the specified port number.
593  *
594  * Returns:
595  *    0: Success. The USB device should now be at address zero.
596  * Else: Failure. No USB device is present and the USB port should be
597  *       disabled.
598  *------------------------------------------------------------------------*/
599 usb_error_t
600 usbd_req_reset_port(struct usb_device *udev, struct mtx *mtx, uint8_t port)
601 {
602 	struct usb_port_status ps;
603 	usb_error_t err;
604 	uint16_t n;
605 
606 #if USB_DEBUG
607 	uint16_t pr_poll_delay;
608 	uint16_t pr_recovery_delay;
609 
610 #endif
611 	err = usbd_req_set_port_feature(udev, mtx, port, UHF_PORT_RESET);
612 	if (err) {
613 		goto done;
614 	}
615 #if USB_DEBUG
616 	/* range check input parameters */
617 	pr_poll_delay = usb_pr_poll_delay;
618 	if (pr_poll_delay < 1) {
619 		pr_poll_delay = 1;
620 	} else if (pr_poll_delay > 1000) {
621 		pr_poll_delay = 1000;
622 	}
623 	pr_recovery_delay = usb_pr_recovery_delay;
624 	if (pr_recovery_delay > 1000) {
625 		pr_recovery_delay = 1000;
626 	}
627 #endif
628 	n = 0;
629 	while (1) {
630 #if USB_DEBUG
631 		/* wait for the device to recover from reset */
632 		usb_pause_mtx(mtx, USB_MS_TO_TICKS(pr_poll_delay));
633 		n += pr_poll_delay;
634 #else
635 		/* wait for the device to recover from reset */
636 		usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_PORT_RESET_DELAY));
637 		n += USB_PORT_RESET_DELAY;
638 #endif
639 		err = usbd_req_get_port_status(udev, mtx, &ps, port);
640 		if (err) {
641 			goto done;
642 		}
643 		/* if the device disappeared, just give up */
644 		if (!(UGETW(ps.wPortStatus) & UPS_CURRENT_CONNECT_STATUS)) {
645 			goto done;
646 		}
647 		/* check if reset is complete */
648 		if (UGETW(ps.wPortChange) & UPS_C_PORT_RESET) {
649 			break;
650 		}
651 		/* check for timeout */
652 		if (n > 1000) {
653 			n = 0;
654 			break;
655 		}
656 	}
657 
658 	/* clear port reset first */
659 	err = usbd_req_clear_port_feature(
660 	    udev, mtx, port, UHF_C_PORT_RESET);
661 	if (err) {
662 		goto done;
663 	}
664 	/* check for timeout */
665 	if (n == 0) {
666 		err = USB_ERR_TIMEOUT;
667 		goto done;
668 	}
669 #if USB_DEBUG
670 	/* wait for the device to recover from reset */
671 	usb_pause_mtx(mtx, USB_MS_TO_TICKS(pr_recovery_delay));
672 #else
673 	/* wait for the device to recover from reset */
674 	usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_PORT_RESET_RECOVERY));
675 #endif
676 
677 done:
678 	DPRINTFN(2, "port %d reset returning error=%s\n",
679 	    port, usbd_errstr(err));
680 	return (err);
681 }
682 
683 /*------------------------------------------------------------------------*
684  *	usbd_req_get_desc
685  *
686  * This function can be used to retrieve USB descriptors. It contains
687  * some additional logic like zeroing of missing descriptor bytes and
688  * retrying an USB descriptor in case of failure. The "min_len"
689  * argument specifies the minimum descriptor length. The "max_len"
690  * argument specifies the maximum descriptor length. If the real
691  * descriptor length is less than the minimum length the missing
692  * byte(s) will be zeroed. The type field, the second byte of the USB
693  * descriptor, will get forced to the correct type. If the "actlen"
694  * pointer is non-NULL, the actual length of the transfer will get
695  * stored in the 16-bit unsigned integer which it is pointing to. The
696  * first byte of the descriptor will not get updated. If the "actlen"
697  * pointer is NULL the first byte of the descriptor will get updated
698  * to reflect the actual length instead. If "min_len" is not equal to
699  * "max_len" then this function will try to retrive the beginning of
700  * the descriptor and base the maximum length on the first byte of the
701  * descriptor.
702  *
703  * Returns:
704  *    0: Success
705  * Else: Failure
706  *------------------------------------------------------------------------*/
707 usb_error_t
708 usbd_req_get_desc(struct usb_device *udev,
709     struct mtx *mtx, uint16_t *actlen, void *desc,
710     uint16_t min_len, uint16_t max_len,
711     uint16_t id, uint8_t type, uint8_t index,
712     uint8_t retries)
713 {
714 	struct usb_device_request req;
715 	uint8_t *buf;
716 	usb_error_t err;
717 
718 	DPRINTFN(4, "id=%d, type=%d, index=%d, max_len=%d\n",
719 	    id, type, index, max_len);
720 
721 	req.bmRequestType = UT_READ_DEVICE;
722 	req.bRequest = UR_GET_DESCRIPTOR;
723 	USETW2(req.wValue, type, index);
724 	USETW(req.wIndex, id);
725 
726 	while (1) {
727 
728 		if ((min_len < 2) || (max_len < 2)) {
729 			err = USB_ERR_INVAL;
730 			goto done;
731 		}
732 		USETW(req.wLength, min_len);
733 
734 		err = usbd_do_request_flags(udev, mtx, &req,
735 		    desc, 0, NULL, 1000);
736 
737 		if (err) {
738 			if (!retries) {
739 				goto done;
740 			}
741 			retries--;
742 
743 			usb_pause_mtx(mtx, hz / 5);
744 
745 			continue;
746 		}
747 		buf = desc;
748 
749 		if (min_len == max_len) {
750 
751 			/* enforce correct length */
752 			if ((buf[0] > min_len) && (actlen == NULL))
753 				buf[0] = min_len;
754 
755 			/* enforce correct type */
756 			buf[1] = type;
757 
758 			goto done;
759 		}
760 		/* range check */
761 
762 		if (max_len > buf[0]) {
763 			max_len = buf[0];
764 		}
765 		/* zero minimum data */
766 
767 		while (min_len > max_len) {
768 			min_len--;
769 			buf[min_len] = 0;
770 		}
771 
772 		/* set new minimum length */
773 
774 		min_len = max_len;
775 	}
776 done:
777 	if (actlen != NULL) {
778 		if (err)
779 			*actlen = 0;
780 		else
781 			*actlen = min_len;
782 	}
783 	return (err);
784 }
785 
786 /*------------------------------------------------------------------------*
787  *	usbd_req_get_string_any
788  *
789  * This function will return the string given by "string_index"
790  * using the first language ID. The maximum length "len" includes
791  * the terminating zero. The "len" argument should be twice as
792  * big pluss 2 bytes, compared with the actual maximum string length !
793  *
794  * Returns:
795  *    0: Success
796  * Else: Failure
797  *------------------------------------------------------------------------*/
798 usb_error_t
799 usbd_req_get_string_any(struct usb_device *udev, struct mtx *mtx, char *buf,
800     uint16_t len, uint8_t string_index)
801 {
802 	char *s;
803 	uint8_t *temp;
804 	uint16_t i;
805 	uint16_t n;
806 	uint16_t c;
807 	uint8_t swap;
808 	usb_error_t err;
809 
810 	if (len == 0) {
811 		/* should not happen */
812 		return (USB_ERR_NORMAL_COMPLETION);
813 	}
814 	if (string_index == 0) {
815 		/* this is the language table */
816 		buf[0] = 0;
817 		return (USB_ERR_INVAL);
818 	}
819 	if (udev->flags.no_strings) {
820 		buf[0] = 0;
821 		return (USB_ERR_STALLED);
822 	}
823 	err = usbd_req_get_string_desc
824 	    (udev, mtx, buf, len, udev->langid, string_index);
825 	if (err) {
826 		buf[0] = 0;
827 		return (err);
828 	}
829 	temp = (uint8_t *)buf;
830 
831 	if (temp[0] < 2) {
832 		/* string length is too short */
833 		buf[0] = 0;
834 		return (USB_ERR_INVAL);
835 	}
836 	/* reserve one byte for terminating zero */
837 	len--;
838 
839 	/* find maximum length */
840 	s = buf;
841 	n = (temp[0] / 2) - 1;
842 	if (n > len) {
843 		n = len;
844 	}
845 	/* skip descriptor header */
846 	temp += 2;
847 
848 	/* reset swap state */
849 	swap = 3;
850 
851 	/* convert and filter */
852 	for (i = 0; (i != n); i++) {
853 		c = UGETW(temp + (2 * i));
854 
855 		/* convert from Unicode, handle buggy strings */
856 		if (((c & 0xff00) == 0) && (swap & 1)) {
857 			/* Little Endian, default */
858 			*s = c;
859 			swap = 1;
860 		} else if (((c & 0x00ff) == 0) && (swap & 2)) {
861 			/* Big Endian */
862 			*s = c >> 8;
863 			swap = 2;
864 		} else {
865 			/* silently skip bad character */
866 			continue;
867 		}
868 
869 		/*
870 		 * Filter by default - we don't allow greater and less than
871 		 * signs because they might confuse the dmesg printouts!
872 		 */
873 		if ((*s == '<') || (*s == '>') || (!isprint(*s))) {
874 			/* silently skip bad character */
875 			continue;
876 		}
877 		s++;
878 	}
879 	*s = 0;				/* zero terminate resulting string */
880 	return (USB_ERR_NORMAL_COMPLETION);
881 }
882 
883 /*------------------------------------------------------------------------*
884  *	usbd_req_get_string_desc
885  *
886  * If you don't know the language ID, consider using
887  * "usbd_req_get_string_any()".
888  *
889  * Returns:
890  *    0: Success
891  * Else: Failure
892  *------------------------------------------------------------------------*/
893 usb_error_t
894 usbd_req_get_string_desc(struct usb_device *udev, struct mtx *mtx, void *sdesc,
895     uint16_t max_len, uint16_t lang_id,
896     uint8_t string_index)
897 {
898 	return (usbd_req_get_desc(udev, mtx, NULL, sdesc, 2, max_len, lang_id,
899 	    UDESC_STRING, string_index, 0));
900 }
901 
902 /*------------------------------------------------------------------------*
903  *	usbd_req_get_config_desc_ptr
904  *
905  * This function is used in device side mode to retrieve the pointer
906  * to the generated config descriptor. This saves allocating space for
907  * an additional config descriptor when setting the configuration.
908  *
909  * Returns:
910  *    0: Success
911  * Else: Failure
912  *------------------------------------------------------------------------*/
913 usb_error_t
914 usbd_req_get_descriptor_ptr(struct usb_device *udev,
915     struct usb_config_descriptor **ppcd, uint16_t wValue)
916 {
917 	struct usb_device_request req;
918 	usb_handle_req_t *hr_func;
919 	const void *ptr;
920 	uint16_t len;
921 	usb_error_t err;
922 
923 	req.bmRequestType = UT_READ_DEVICE;
924 	req.bRequest = UR_GET_DESCRIPTOR;
925 	USETW(req.wValue, wValue);
926 	USETW(req.wIndex, 0);
927 	USETW(req.wLength, 0);
928 
929 	ptr = NULL;
930 	len = 0;
931 
932 	hr_func = usbd_get_hr_func(udev);
933 
934 	if (hr_func == NULL)
935 		err = USB_ERR_INVAL;
936 	else {
937 		USB_BUS_LOCK(udev->bus);
938 		err = (hr_func) (udev, &req, &ptr, &len);
939 		USB_BUS_UNLOCK(udev->bus);
940 	}
941 
942 	if (err)
943 		ptr = NULL;
944 	else if (ptr == NULL)
945 		err = USB_ERR_INVAL;
946 
947 	*ppcd = __DECONST(struct usb_config_descriptor *, ptr);
948 
949 	return (err);
950 }
951 
952 /*------------------------------------------------------------------------*
953  *	usbd_req_get_config_desc
954  *
955  * Returns:
956  *    0: Success
957  * Else: Failure
958  *------------------------------------------------------------------------*/
959 usb_error_t
960 usbd_req_get_config_desc(struct usb_device *udev, struct mtx *mtx,
961     struct usb_config_descriptor *d, uint8_t conf_index)
962 {
963 	usb_error_t err;
964 
965 	DPRINTFN(4, "confidx=%d\n", conf_index);
966 
967 	err = usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
968 	    sizeof(*d), 0, UDESC_CONFIG, conf_index, 0);
969 	if (err) {
970 		goto done;
971 	}
972 	/* Extra sanity checking */
973 	if (UGETW(d->wTotalLength) < sizeof(*d)) {
974 		err = USB_ERR_INVAL;
975 	}
976 done:
977 	return (err);
978 }
979 
980 /*------------------------------------------------------------------------*
981  *	usbd_req_get_config_desc_full
982  *
983  * This function gets the complete USB configuration descriptor and
984  * ensures that "wTotalLength" is correct.
985  *
986  * Returns:
987  *    0: Success
988  * Else: Failure
989  *------------------------------------------------------------------------*/
990 usb_error_t
991 usbd_req_get_config_desc_full(struct usb_device *udev, struct mtx *mtx,
992     struct usb_config_descriptor **ppcd, struct malloc_type *mtype,
993     uint8_t index)
994 {
995 	struct usb_config_descriptor cd;
996 	struct usb_config_descriptor *cdesc;
997 	uint16_t len;
998 	usb_error_t err;
999 
1000 	DPRINTFN(4, "index=%d\n", index);
1001 
1002 	*ppcd = NULL;
1003 
1004 	err = usbd_req_get_config_desc(udev, mtx, &cd, index);
1005 	if (err) {
1006 		return (err);
1007 	}
1008 	/* get full descriptor */
1009 	len = UGETW(cd.wTotalLength);
1010 	if (len < sizeof(*cdesc)) {
1011 		/* corrupt descriptor */
1012 		return (USB_ERR_INVAL);
1013 	}
1014 	cdesc = malloc(len, mtype, M_WAITOK);
1015 	if (cdesc == NULL) {
1016 		return (USB_ERR_NOMEM);
1017 	}
1018 	err = usbd_req_get_desc(udev, mtx, NULL, cdesc, len, len, 0,
1019 	    UDESC_CONFIG, index, 3);
1020 	if (err) {
1021 		free(cdesc, mtype);
1022 		return (err);
1023 	}
1024 	/* make sure that the device is not fooling us: */
1025 	USETW(cdesc->wTotalLength, len);
1026 
1027 	*ppcd = cdesc;
1028 
1029 	return (0);			/* success */
1030 }
1031 
1032 /*------------------------------------------------------------------------*
1033  *	usbd_req_get_device_desc
1034  *
1035  * Returns:
1036  *    0: Success
1037  * Else: Failure
1038  *------------------------------------------------------------------------*/
1039 usb_error_t
1040 usbd_req_get_device_desc(struct usb_device *udev, struct mtx *mtx,
1041     struct usb_device_descriptor *d)
1042 {
1043 	DPRINTFN(4, "\n");
1044 	return (usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
1045 	    sizeof(*d), 0, UDESC_DEVICE, 0, 3));
1046 }
1047 
1048 /*------------------------------------------------------------------------*
1049  *	usbd_req_get_alt_interface_no
1050  *
1051  * Returns:
1052  *    0: Success
1053  * Else: Failure
1054  *------------------------------------------------------------------------*/
1055 usb_error_t
1056 usbd_req_get_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1057     uint8_t *alt_iface_no, uint8_t iface_index)
1058 {
1059 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1060 	struct usb_device_request req;
1061 
1062 	if ((iface == NULL) || (iface->idesc == NULL))
1063 		return (USB_ERR_INVAL);
1064 
1065 	req.bmRequestType = UT_READ_INTERFACE;
1066 	req.bRequest = UR_GET_INTERFACE;
1067 	USETW(req.wValue, 0);
1068 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1069 	req.wIndex[1] = 0;
1070 	USETW(req.wLength, 1);
1071 	return (usbd_do_request(udev, mtx, &req, alt_iface_no));
1072 }
1073 
1074 /*------------------------------------------------------------------------*
1075  *	usbd_req_set_alt_interface_no
1076  *
1077  * Returns:
1078  *    0: Success
1079  * Else: Failure
1080  *------------------------------------------------------------------------*/
1081 usb_error_t
1082 usbd_req_set_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1083     uint8_t iface_index, uint8_t alt_no)
1084 {
1085 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1086 	struct usb_device_request req;
1087 
1088 	if ((iface == NULL) || (iface->idesc == NULL))
1089 		return (USB_ERR_INVAL);
1090 
1091 	req.bmRequestType = UT_WRITE_INTERFACE;
1092 	req.bRequest = UR_SET_INTERFACE;
1093 	req.wValue[0] = alt_no;
1094 	req.wValue[1] = 0;
1095 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1096 	req.wIndex[1] = 0;
1097 	USETW(req.wLength, 0);
1098 	return (usbd_do_request(udev, mtx, &req, 0));
1099 }
1100 
1101 /*------------------------------------------------------------------------*
1102  *	usbd_req_get_device_status
1103  *
1104  * Returns:
1105  *    0: Success
1106  * Else: Failure
1107  *------------------------------------------------------------------------*/
1108 usb_error_t
1109 usbd_req_get_device_status(struct usb_device *udev, struct mtx *mtx,
1110     struct usb_status *st)
1111 {
1112 	struct usb_device_request req;
1113 
1114 	req.bmRequestType = UT_READ_DEVICE;
1115 	req.bRequest = UR_GET_STATUS;
1116 	USETW(req.wValue, 0);
1117 	USETW(req.wIndex, 0);
1118 	USETW(req.wLength, sizeof(*st));
1119 	return (usbd_do_request(udev, mtx, &req, st));
1120 }
1121 
1122 /*------------------------------------------------------------------------*
1123  *	usbd_req_get_hub_descriptor
1124  *
1125  * Returns:
1126  *    0: Success
1127  * Else: Failure
1128  *------------------------------------------------------------------------*/
1129 usb_error_t
1130 usbd_req_get_hub_descriptor(struct usb_device *udev, struct mtx *mtx,
1131     struct usb_hub_descriptor *hd, uint8_t nports)
1132 {
1133 	struct usb_device_request req;
1134 	uint16_t len = (nports + 7 + (8 * 8)) / 8;
1135 
1136 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1137 	req.bRequest = UR_GET_DESCRIPTOR;
1138 	USETW2(req.wValue, UDESC_HUB, 0);
1139 	USETW(req.wIndex, 0);
1140 	USETW(req.wLength, len);
1141 	return (usbd_do_request(udev, mtx, &req, hd));
1142 }
1143 
1144 /*------------------------------------------------------------------------*
1145  *	usbd_req_get_hub_status
1146  *
1147  * Returns:
1148  *    0: Success
1149  * Else: Failure
1150  *------------------------------------------------------------------------*/
1151 usb_error_t
1152 usbd_req_get_hub_status(struct usb_device *udev, struct mtx *mtx,
1153     struct usb_hub_status *st)
1154 {
1155 	struct usb_device_request req;
1156 
1157 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1158 	req.bRequest = UR_GET_STATUS;
1159 	USETW(req.wValue, 0);
1160 	USETW(req.wIndex, 0);
1161 	USETW(req.wLength, sizeof(struct usb_hub_status));
1162 	return (usbd_do_request(udev, mtx, &req, st));
1163 }
1164 
1165 /*------------------------------------------------------------------------*
1166  *	usbd_req_set_address
1167  *
1168  * This function is used to set the address for an USB device. After
1169  * port reset the USB device will respond at address zero.
1170  *
1171  * Returns:
1172  *    0: Success
1173  * Else: Failure
1174  *------------------------------------------------------------------------*/
1175 usb_error_t
1176 usbd_req_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t addr)
1177 {
1178 	struct usb_device_request req;
1179 
1180 	DPRINTFN(6, "setting device address=%d\n", addr);
1181 
1182 	req.bmRequestType = UT_WRITE_DEVICE;
1183 	req.bRequest = UR_SET_ADDRESS;
1184 	USETW(req.wValue, addr);
1185 	USETW(req.wIndex, 0);
1186 	USETW(req.wLength, 0);
1187 
1188 	/* Setting the address should not take more than 1 second ! */
1189 	return (usbd_do_request_flags(udev, mtx, &req, NULL,
1190 	    USB_DELAY_STATUS_STAGE, NULL, 1000));
1191 }
1192 
1193 /*------------------------------------------------------------------------*
1194  *	usbd_req_get_port_status
1195  *
1196  * Returns:
1197  *    0: Success
1198  * Else: Failure
1199  *------------------------------------------------------------------------*/
1200 usb_error_t
1201 usbd_req_get_port_status(struct usb_device *udev, struct mtx *mtx,
1202     struct usb_port_status *ps, uint8_t port)
1203 {
1204 	struct usb_device_request req;
1205 
1206 	req.bmRequestType = UT_READ_CLASS_OTHER;
1207 	req.bRequest = UR_GET_STATUS;
1208 	USETW(req.wValue, 0);
1209 	req.wIndex[0] = port;
1210 	req.wIndex[1] = 0;
1211 	USETW(req.wLength, sizeof *ps);
1212 	return (usbd_do_request(udev, mtx, &req, ps));
1213 }
1214 
1215 /*------------------------------------------------------------------------*
1216  *	usbd_req_clear_hub_feature
1217  *
1218  * Returns:
1219  *    0: Success
1220  * Else: Failure
1221  *------------------------------------------------------------------------*/
1222 usb_error_t
1223 usbd_req_clear_hub_feature(struct usb_device *udev, struct mtx *mtx,
1224     uint16_t sel)
1225 {
1226 	struct usb_device_request req;
1227 
1228 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1229 	req.bRequest = UR_CLEAR_FEATURE;
1230 	USETW(req.wValue, sel);
1231 	USETW(req.wIndex, 0);
1232 	USETW(req.wLength, 0);
1233 	return (usbd_do_request(udev, mtx, &req, 0));
1234 }
1235 
1236 /*------------------------------------------------------------------------*
1237  *	usbd_req_set_hub_feature
1238  *
1239  * Returns:
1240  *    0: Success
1241  * Else: Failure
1242  *------------------------------------------------------------------------*/
1243 usb_error_t
1244 usbd_req_set_hub_feature(struct usb_device *udev, struct mtx *mtx,
1245     uint16_t sel)
1246 {
1247 	struct usb_device_request req;
1248 
1249 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1250 	req.bRequest = UR_SET_FEATURE;
1251 	USETW(req.wValue, sel);
1252 	USETW(req.wIndex, 0);
1253 	USETW(req.wLength, 0);
1254 	return (usbd_do_request(udev, mtx, &req, 0));
1255 }
1256 
1257 /*------------------------------------------------------------------------*
1258  *	usbd_req_clear_port_feature
1259  *
1260  * Returns:
1261  *    0: Success
1262  * Else: Failure
1263  *------------------------------------------------------------------------*/
1264 usb_error_t
1265 usbd_req_clear_port_feature(struct usb_device *udev, struct mtx *mtx,
1266     uint8_t port, uint16_t sel)
1267 {
1268 	struct usb_device_request req;
1269 
1270 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1271 	req.bRequest = UR_CLEAR_FEATURE;
1272 	USETW(req.wValue, sel);
1273 	req.wIndex[0] = port;
1274 	req.wIndex[1] = 0;
1275 	USETW(req.wLength, 0);
1276 	return (usbd_do_request(udev, mtx, &req, 0));
1277 }
1278 
1279 /*------------------------------------------------------------------------*
1280  *	usbd_req_set_port_feature
1281  *
1282  * Returns:
1283  *    0: Success
1284  * Else: Failure
1285  *------------------------------------------------------------------------*/
1286 usb_error_t
1287 usbd_req_set_port_feature(struct usb_device *udev, struct mtx *mtx,
1288     uint8_t port, uint16_t sel)
1289 {
1290 	struct usb_device_request req;
1291 
1292 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1293 	req.bRequest = UR_SET_FEATURE;
1294 	USETW(req.wValue, sel);
1295 	req.wIndex[0] = port;
1296 	req.wIndex[1] = 0;
1297 	USETW(req.wLength, 0);
1298 	return (usbd_do_request(udev, mtx, &req, 0));
1299 }
1300 
1301 /*------------------------------------------------------------------------*
1302  *	usbd_req_set_protocol
1303  *
1304  * Returns:
1305  *    0: Success
1306  * Else: Failure
1307  *------------------------------------------------------------------------*/
1308 usb_error_t
1309 usbd_req_set_protocol(struct usb_device *udev, struct mtx *mtx,
1310     uint8_t iface_index, uint16_t report)
1311 {
1312 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1313 	struct usb_device_request req;
1314 
1315 	if ((iface == NULL) || (iface->idesc == NULL)) {
1316 		return (USB_ERR_INVAL);
1317 	}
1318 	DPRINTFN(5, "iface=%p, report=%d, endpt=%d\n",
1319 	    iface, report, iface->idesc->bInterfaceNumber);
1320 
1321 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1322 	req.bRequest = UR_SET_PROTOCOL;
1323 	USETW(req.wValue, report);
1324 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1325 	req.wIndex[1] = 0;
1326 	USETW(req.wLength, 0);
1327 	return (usbd_do_request(udev, mtx, &req, 0));
1328 }
1329 
1330 /*------------------------------------------------------------------------*
1331  *	usbd_req_set_report
1332  *
1333  * Returns:
1334  *    0: Success
1335  * Else: Failure
1336  *------------------------------------------------------------------------*/
1337 usb_error_t
1338 usbd_req_set_report(struct usb_device *udev, struct mtx *mtx, void *data, uint16_t len,
1339     uint8_t iface_index, uint8_t type, uint8_t id)
1340 {
1341 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1342 	struct usb_device_request req;
1343 
1344 	if ((iface == NULL) || (iface->idesc == NULL)) {
1345 		return (USB_ERR_INVAL);
1346 	}
1347 	DPRINTFN(5, "len=%d\n", len);
1348 
1349 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1350 	req.bRequest = UR_SET_REPORT;
1351 	USETW2(req.wValue, type, id);
1352 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1353 	req.wIndex[1] = 0;
1354 	USETW(req.wLength, len);
1355 	return (usbd_do_request(udev, mtx, &req, data));
1356 }
1357 
1358 /*------------------------------------------------------------------------*
1359  *	usbd_req_get_report
1360  *
1361  * Returns:
1362  *    0: Success
1363  * Else: Failure
1364  *------------------------------------------------------------------------*/
1365 usb_error_t
1366 usbd_req_get_report(struct usb_device *udev, struct mtx *mtx, void *data,
1367     uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id)
1368 {
1369 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1370 	struct usb_device_request req;
1371 
1372 	if ((iface == NULL) || (iface->idesc == NULL) || (id == 0)) {
1373 		return (USB_ERR_INVAL);
1374 	}
1375 	DPRINTFN(5, "len=%d\n", len);
1376 
1377 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1378 	req.bRequest = UR_GET_REPORT;
1379 	USETW2(req.wValue, type, id);
1380 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1381 	req.wIndex[1] = 0;
1382 	USETW(req.wLength, len);
1383 	return (usbd_do_request(udev, mtx, &req, data));
1384 }
1385 
1386 /*------------------------------------------------------------------------*
1387  *	usbd_req_set_idle
1388  *
1389  * Returns:
1390  *    0: Success
1391  * Else: Failure
1392  *------------------------------------------------------------------------*/
1393 usb_error_t
1394 usbd_req_set_idle(struct usb_device *udev, struct mtx *mtx,
1395     uint8_t iface_index, uint8_t duration, uint8_t id)
1396 {
1397 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1398 	struct usb_device_request req;
1399 
1400 	if ((iface == NULL) || (iface->idesc == NULL)) {
1401 		return (USB_ERR_INVAL);
1402 	}
1403 	DPRINTFN(5, "%d %d\n", duration, id);
1404 
1405 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1406 	req.bRequest = UR_SET_IDLE;
1407 	USETW2(req.wValue, duration, id);
1408 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1409 	req.wIndex[1] = 0;
1410 	USETW(req.wLength, 0);
1411 	return (usbd_do_request(udev, mtx, &req, 0));
1412 }
1413 
1414 /*------------------------------------------------------------------------*
1415  *	usbd_req_get_report_descriptor
1416  *
1417  * Returns:
1418  *    0: Success
1419  * Else: Failure
1420  *------------------------------------------------------------------------*/
1421 usb_error_t
1422 usbd_req_get_report_descriptor(struct usb_device *udev, struct mtx *mtx,
1423     void *d, uint16_t size, uint8_t iface_index)
1424 {
1425 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1426 	struct usb_device_request req;
1427 
1428 	if ((iface == NULL) || (iface->idesc == NULL)) {
1429 		return (USB_ERR_INVAL);
1430 	}
1431 	req.bmRequestType = UT_READ_INTERFACE;
1432 	req.bRequest = UR_GET_DESCRIPTOR;
1433 	USETW2(req.wValue, UDESC_REPORT, 0);	/* report id should be 0 */
1434 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1435 	req.wIndex[1] = 0;
1436 	USETW(req.wLength, size);
1437 	return (usbd_do_request(udev, mtx, &req, d));
1438 }
1439 
1440 /*------------------------------------------------------------------------*
1441  *	usbd_req_set_config
1442  *
1443  * This function is used to select the current configuration number in
1444  * both USB device side mode and USB host side mode. When setting the
1445  * configuration the function of the interfaces can change.
1446  *
1447  * Returns:
1448  *    0: Success
1449  * Else: Failure
1450  *------------------------------------------------------------------------*/
1451 usb_error_t
1452 usbd_req_set_config(struct usb_device *udev, struct mtx *mtx, uint8_t conf)
1453 {
1454 	struct usb_device_request req;
1455 
1456 	DPRINTF("setting config %d\n", conf);
1457 
1458 	/* do "set configuration" request */
1459 
1460 	req.bmRequestType = UT_WRITE_DEVICE;
1461 	req.bRequest = UR_SET_CONFIG;
1462 	req.wValue[0] = conf;
1463 	req.wValue[1] = 0;
1464 	USETW(req.wIndex, 0);
1465 	USETW(req.wLength, 0);
1466 	return (usbd_do_request(udev, mtx, &req, 0));
1467 }
1468 
1469 /*------------------------------------------------------------------------*
1470  *	usbd_req_get_config
1471  *
1472  * Returns:
1473  *    0: Success
1474  * Else: Failure
1475  *------------------------------------------------------------------------*/
1476 usb_error_t
1477 usbd_req_get_config(struct usb_device *udev, struct mtx *mtx, uint8_t *pconf)
1478 {
1479 	struct usb_device_request req;
1480 
1481 	req.bmRequestType = UT_READ_DEVICE;
1482 	req.bRequest = UR_GET_CONFIG;
1483 	USETW(req.wValue, 0);
1484 	USETW(req.wIndex, 0);
1485 	USETW(req.wLength, 1);
1486 	return (usbd_do_request(udev, mtx, &req, pconf));
1487 }
1488 
1489 /*------------------------------------------------------------------------*
1490  *	usbd_req_re_enumerate
1491  *
1492  * NOTE: After this function returns the hardware is in the
1493  * unconfigured state! The application is responsible for setting a
1494  * new configuration.
1495  *
1496  * Returns:
1497  *    0: Success
1498  * Else: Failure
1499  *------------------------------------------------------------------------*/
1500 usb_error_t
1501 usbd_req_re_enumerate(struct usb_device *udev, struct mtx *mtx)
1502 {
1503 	struct usb_device *parent_hub;
1504 	usb_error_t err;
1505 	uint8_t old_addr;
1506 	uint8_t do_retry = 1;
1507 
1508 	if (udev->flags.usb_mode != USB_MODE_HOST) {
1509 		return (USB_ERR_INVAL);
1510 	}
1511 	old_addr = udev->address;
1512 	parent_hub = udev->parent_hub;
1513 	if (parent_hub == NULL) {
1514 		return (USB_ERR_INVAL);
1515 	}
1516 retry:
1517 	err = usbd_req_reset_port(parent_hub, mtx, udev->port_no);
1518 	if (err) {
1519 		DPRINTFN(0, "addr=%d, port reset failed, %s\n",
1520 		    old_addr, usbd_errstr(err));
1521 		goto done;
1522 	}
1523 	/*
1524 	 * After that the port has been reset our device should be at
1525 	 * address zero:
1526 	 */
1527 	udev->address = USB_START_ADDR;
1528 
1529 	/* reset "bMaxPacketSize" */
1530 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1531 
1532 	/*
1533 	 * Restore device address:
1534 	 */
1535 	err = usbd_req_set_address(udev, mtx, old_addr);
1536 	if (err) {
1537 		/* XXX ignore any errors! */
1538 		DPRINTFN(0, "addr=%d, set address failed! (%s, ignored)\n",
1539 		    old_addr, usbd_errstr(err));
1540 	}
1541 	/* restore device address */
1542 	udev->address = old_addr;
1543 
1544 	/* allow device time to set new address */
1545 	usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1546 
1547 	/* get the device descriptor */
1548 	err = usbd_req_get_desc(udev, mtx, NULL, &udev->ddesc,
1549 	    USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1550 	if (err) {
1551 		DPRINTFN(0, "getting device descriptor "
1552 		    "at addr %d failed, %s\n", udev->address,
1553 		    usbd_errstr(err));
1554 		goto done;
1555 	}
1556 	/* get the full device descriptor */
1557 	err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1558 	if (err) {
1559 		DPRINTFN(0, "addr=%d, getting device "
1560 		    "descriptor failed, %s\n", old_addr,
1561 		    usbd_errstr(err));
1562 		goto done;
1563 	}
1564 done:
1565 	if (err && do_retry) {
1566 		/* give the USB firmware some time to load */
1567 		usb_pause_mtx(mtx, hz / 2);
1568 		/* no more retries after this retry */
1569 		do_retry = 0;
1570 		/* try again */
1571 		goto retry;
1572 	}
1573 	/* restore address */
1574 	udev->address = old_addr;
1575 	return (err);
1576 }
1577 
1578 /*------------------------------------------------------------------------*
1579  *	usbd_req_clear_device_feature
1580  *
1581  * Returns:
1582  *    0: Success
1583  * Else: Failure
1584  *------------------------------------------------------------------------*/
1585 usb_error_t
1586 usbd_req_clear_device_feature(struct usb_device *udev, struct mtx *mtx,
1587     uint16_t sel)
1588 {
1589 	struct usb_device_request req;
1590 
1591 	req.bmRequestType = UT_WRITE_DEVICE;
1592 	req.bRequest = UR_CLEAR_FEATURE;
1593 	USETW(req.wValue, sel);
1594 	USETW(req.wIndex, 0);
1595 	USETW(req.wLength, 0);
1596 	return (usbd_do_request(udev, mtx, &req, 0));
1597 }
1598 
1599 /*------------------------------------------------------------------------*
1600  *	usbd_req_set_device_feature
1601  *
1602  * Returns:
1603  *    0: Success
1604  * Else: Failure
1605  *------------------------------------------------------------------------*/
1606 usb_error_t
1607 usbd_req_set_device_feature(struct usb_device *udev, struct mtx *mtx,
1608     uint16_t sel)
1609 {
1610 	struct usb_device_request req;
1611 
1612 	req.bmRequestType = UT_WRITE_DEVICE;
1613 	req.bRequest = UR_SET_FEATURE;
1614 	USETW(req.wValue, sel);
1615 	USETW(req.wIndex, 0);
1616 	USETW(req.wLength, 0);
1617 	return (usbd_do_request(udev, mtx, &req, 0));
1618 }
1619